Vue实现动态tab标签滚动定位跟随动画

尽管目前大多数 UI 框架都有 tab 组件,但是有时候并不能满足需求,或者需要对组件进行二次开发,考虑到总总原因,还是决定自己亲手写一个算了。

Vue实现动态tab标签滚动定位跟随动画_第1张图片

Element.getBoundingClientRect()
实现其实不难,这里只需使用 getBoundingClientRect 这个函数就可以,根据文档的介绍,该方法返回元素的大小及其相对于视窗的位置。

看图后应该不难理解,图中 0,0 指定是浏览器中窗口的左上角,因此使用该函数后元素返回的 top、bottom、left、right 都是相对窗口左上角的位置。

设计分析

由于 tab 的数量不是固定的,很有可能超出元素边界,所以需要用外层来包裹 tab 层,并且是 overflow: hidden,滚动效果通过改变 css 中的 translate 来实现。

实现分析

如何计算滚动位置?只要通过 getBoundingClientRect 取得各元素的位置后,再判断 tab 是否超出父级元素的边界,然后根据当前选中的 tab 位置计算出向前或向后需要滚动多少像素。

less样式

.cat-tabbar {
    display: flex;
    align-items: center;
    width: 100%;
    border-top: 1px solid #f2f2f2;
    padding-top: 8px;

    &__arrow {
        display:flex;
        align-items:center;
        height: 40px;
        line-height: 0;
        padding: 0 16px;
        cursor: pointer;
        color: #fff;
        background-color: #000;

        &:hover {
            color: dodgerblue;
        }
    }

    &__container {
        flex: 1;
        overflow: hidden;
    }

    &__list {
        display: flex;
        white-space: nowrap;
        transition: transform 200ms;
    }

    &__item {
        display: flex;
        align-items: stretch;
        height: 40px;
        cursor: pointer;
        border-top-left-radius: 4px;
        border-top-right-radius: 4px;

        .tab-text {
            display: flex;
            justify-content: center;
            align-items: center;
            padding-left: 20px;
            color: #777;
            // 既是最后一个,又是第一个
            &:last-child:first-child {
                padding-right: 20px;
            }
        }

        .tab-close {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 40px;
            height: 100%;
            color: #313b46;

            span {
                font-size: 12px;
                transition: color 200ms;
            }

            span:hover {
                color: red;
            }
        }
    }

    &__item.is-active {
        background-color: dodgerblue;

        .tab-text {
            color: #fff;
        }

        .tab-close {
            color: #fff;
        }
    }
}

你可能感兴趣的:(Vue实现动态tab标签滚动定位跟随动画)