css实现不同菜单选项卡特效
前言:用vue写菜单切换功能,附带css特效,纯手写,不用组件哦~
功能:实现用户点击不同菜单选项卡下面高亮的动画(列出网页上比较常见的两种特效!!!)
先实现特效:
- 从左到右:先附带张图片看看吧(视频不会弄,没那技术~)
点击从1过渡到2
//html
<div class="nav-left" ref="navLeft">
<div class="look-box" ref="lookBox">
<span
class="nav-name"
:class="{ active: activeIndex === index }"
v-for="(item, index) in navList"
:key="item.value"
@click="navClick(item, index)"
>
{{ item[dataFormatter.name] }}
</span>
//竖线
<div class="nav-line" ref="navLine"></div>
</div>
</div>
//js
watch:{
activeIndex: {
handler(val) {
this.$nextTick(() => {
const lookBox = this.$refs.lookBox;
if (!this.$refs.navLine) return;
this.$refs.navLine.style.width = `${lookBox.children[val].offsetWidth}px`;
const allNavWdith = [];
for (let i = 0; i < lookBox.children.length; i++) {
allNavWdith.push(lookBox.children[i].offsetWidth);
}
const sumNavWidth = val === 0 ? 0 : this.toSum(allNavWdith, val - 1);
this.$refs.navLine.style.transform = `translateX(${sumNavWidth}px)`;
});
},
immediate: true,
},
},
motheds:{
toSum(arr, index) {
const sum = arr.reduce((per, cur, currentIndex) => {
if (currentIndex <= index) per += cur;
return per;
}, 0);
let INTERVAL = 24;//两个tab中间的间隔
return arr.length != index ? sum + (index + 1) * INTERVAL : sum + index * INTERVAL ;
},
}
//css
.look-box {
display: inline-flex;
width: 100%;
transform: translateX(0);
position: relative;
span {
margin-right: 24px;
}
span:nth-last-child(1) {
margin-right: 0;
}
}
.nav-line {
background: #0887ff;
position: absolute;
bottom: 0;
height: 2px;
display: inline-block;
transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}
.nav-name {
font-size: 14px;
padding-bottom: 10px;
flex-shrink: 0;
}
.active {
color: #0887ff;
position: relative;
}
2、点击tab,高亮特效从中间往左右两边扩展(主要是css哦!!!)。
//html
<div v-for="item in navArr" :key="item.value" class="tab-item" :class="{'active':activeIndex == item.value}" @click="tabChange(item)">
{{item.label}}
</div>
//js
tabChange(item) {
this.activeIndex = item.value;
},
//css
.tab-item{
cursor: pointer;
margin-right: 20px;
font-size: 14px;
padding-bottom: 8px;
&::after{
content:'';
position: absolute;
left: 50%;
transform: translateX(-50%);
bottom: 0;
width: 0%;
height: 2px;
background:#376BE9;
}
}
.active{
color: #376BE9;
position: relative;
font-weight: 600;
&::after{
transition: width .3s;
width: 100%
}
}
好啦!两种特效就写到这了~