具体效果图如上
因为refs获取元素在小程序环境是不能被使用的,我们只能通过小程序提供的api --
uni.createSelectorQuery()来获取元素位置信息
js部分
updateTabWidth(){
const query = uni.createSelectorQuery().in(this);
query.select('#_tab_' + this.activeIndex).boundingClientRect(res=>{
this.left = res.width/2 + res.width * (this.activeIndex -1) - 16;
}).exec();
},
changeIndex(index){
this.activeIndex = index;
this.updateTabWidth();
}
html部分
<view class="menu">
<view class="item" v-for="item in list" :key="item.id" @tap="changeIndex(item.id)" :id="'_tab_'+item.id">
{{item.name}}
</view>
<view class="lines" :style="{transform: 'translateX(' + left + 'px)'}"></view>
</view>
scss部分
.menu{
position: relative;
display: flex;
align-items: center;
width: 100%;
height: 100rpx;
.item{
width: 33%;
font-size: 32rpx;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #212121;
line-height:50rpx;
text-align: center;
}
.lines{
width: 64rpx;
height: 6rpx;
background: #FFD61E;
border-radius: 4rpx;
transition: .5s cubic-bezier(.215,.61,.355,1);
position: absolute;
bottom: 16rpx;
}
}
实现原理是id选择器标志,获取不同id标志的位置信息,然后计算出下划线需要滑动的距离,加上渐变样式,菜单滑动选择器就实现了。