tab 页签宽度自适应

发布时间 2023-03-24 13:46:23作者: 名字不好起啊

管理系统离不开多 tab ,多 tab 页就有可能因为页数太多导致部分 tab 页被隐藏等功能异常。

这里记录个类似浏览器 tab 页功能样式,多 tab 页时采取压缩 tab 页宽度 及 文本超出 变为 ... 形式:

<!DOCTYPE html>
<html>
<style type="text/css">
    .box {
        margin: 0 auto;
        border: 1px solid #ddd;
        padding: 10px;
        display: flex;
        flex-direction: row;
    }
    .item {
        border: 1px solid #ddd;
        margin-bottom: 20px;
        padding: 10px;
        flex-basis: 100px;
        display: inline-block;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
    }
</style>
<body>
    <div class="box"></div>

    <script>
        window.onload = () => {
            let box = document.getElementsByClassName('box')[0];
            let frag = document.createDocumentFragment();
            for (let i = 0; i < 9; i++) {
                let item = document.createElement('div');
                item.className = 'item';
                item.title = item.innerHTML = Math.random();
                frag.appendChild(item);
            }
            box.appendChild(frag);
        }
    </script>

</body>
</html>

主要用到的就是 【 flex-basis 】

 

页面足够宽时,默认宽度展示:

 

不够宽时,压缩展示: