斜边Tab框实现

868 阅读2分钟

总述

每次收到设计师传来的高保真,心里总是默默祈祷,请不要出现奇奇怪怪的tab框~ORZ。呐,这次就接到了个这样的

Video_20220111153308.gif

中间平行四边形,两边直角梯形,对于前端入门小白来说,介不刁难我胖虎嘛,在我废、寝、忘、食的不懈努力下,终于弄了出来。

思路

  1. 使用<ul>和<li>实现,<ul> 设置外边框,并且overflow:hidden
  1. 重点是里面的斜边和多边形背景的实现,斜边边框在其<li>中的伪类before实现,多边形背景使用css的clip属性,在其<li>的伪类after实现。

代码实现

重要的地方已在注释中说明

<ul>
    <li
    v-for="(item, index) in tabHeader"
    :key="index"
    :class="{ active: index === mainActive }"
    @click="handleMainTab(index)"
    >
    {{ item }}
    </li>
</ul>
ul {
    list-style: none;
    display: flex;
    align-items: center;
    margin: 0;
    overflow:hidden;
    li {
        width: 527px;
        height: 36px;
        position: relative;
        line-height: 36px;
        &:not(:first-of-type):before {//第一个tab不需要斜边框,因此将第一个li排除掉
            content: '';
            width: 1px;
            height: 100%;
            position: absolute;
            border: 1px solid #003a65;
            transform: skew(-45deg);
            left: 0;
            transform-origin: bottom;
        }
        &::after {//多边形背景宽度一定要设宽一些,不然无法填充tab项
            //对于超出的宽度,uloverflow已经处理
            content: '';
            width: 107%;
            height: 100%;
            position: absolute;
            left: 0;
            cursor: pointer;
        }
        &:not(:first-of-type, :last-of-type)::after {// 多边形剪裁
            clip-path: polygon(7% 0%, 100% 0%, 94% 100%, 0% 100%);
        }
        &:first-of-type::after {// 第一个tab项多边形剪裁
            clip-path: polygon(0 0, 100% 0, 94% 100%, 0% 100%);
        }
        &:last-of-type::after {// 最后一个tab项多边形剪裁
            clip-path: polygon(7% 0, 100% 0, 100% 100%, 0% 100%);
        }
        &.active::after {
            color: #ffffff;
            background-image: linear-gradient(
                90deg,
                rgba(0, 133, 255, 0.7) 0%,
                rgba(0, 133, 255, 0) 100%
            );
        }
    }
}

总结

clip属性真的是一个很不错的东西,这里推荐一个clip属性的在线生成网站

clip属性在线生成器