<template>
<view >
<scroll-view scroll-x class="nav-tab-wrap" :throttle="false" @scroll="scrollEvent" scroll-with-animation
:scroll-left="scrollLeft">
<view class="nav-tab">
<block v-for="(item,index) in list" :key="index">
<view class="nav-tab-item" :class="{'active':currentIndex==index}" @tap="changeTab(index)">{{item}}
</view>
</block>
<view class="underline" :style="'left:'+ left +'px;width:'+ width +'px;'"></view>
</view>
</scroll-view>
</view>
</template>
<script>
export default {
props: {
list: Array, //导航条的数据
activeIndex: Number //默认选定的值
},
data() {
return {
currentIndex: 0, //当前选中的索引值
left: 0, //滑动条左边距离
width: 0, //滑动条宽度
scrollX: 0, //滚动条的位置
space: uni.upx2px(-35), //滑动条和item的左右间距
scrollLeft: 0, //滚动条到左边的距离
contentScroll: 0 //滚动条的宽度
}
},
mounted() {
let that = this
that.changeTab(0)
},
methods: {
changeTab(num) {
let that = this;
that.currentIndex = num;
let selectorQuery = uni.createSelectorQuery().in(that);
selectorQuery.selectAll('.nav-tab-item').boundingClientRect(function(data) {
// data 为当前选中tab的节点信息
num==0?that.left=0:that.left = data[num].left + that.scrollX + that.space;
that.width = data[num].width;
}).exec();
// 获取滚动条的宽度
selectorQuery.select('.nav-tab-wrap').boundingClientRect(data => {
this.contentScroll = data.width
}).exec()
this.scrollLeft =parseInt(this.left) - parseInt(this.contentScroll / 2) + parseInt(that.width / 2)
setTimeout(res=>{
this.scrollLeft =parseInt(this.left) - parseInt(this.contentScroll / 2) + parseInt(that.width / 2) //再次刷新下横向滚动条。防止出现手机端不居中的情况
},100)
this.$emit('getIndex', num)
},
scrollEvent(e) {
this.scrollX = e.detail.scrollLeft;
}
}
}
</script>
<style lang="less">
scroll-view ::-webkit-scrollbar {
width: 0;
height: 0;
background-color: transparent;
}
.nav-tab-wrap {
max-width: 100%;
white-space: nowrap;
.nav-tab {
position: relative;
.nav-tab-item {
margin-right: 60upx;
line-height: 80upx;
display: inline-block;
color: #989898;
font-size: 28upx;
&.active {
color: #FF6100;
}
}
.underline {
position: absolute;
// width: 40upx;
height: 5upx;
background-color: #FF6100;
// left: 20upx;
bottom: 0;
transition: 0.4s;
}
}
}
</style>
在ios和h5上可以正常使用