效果:
<view class="tabhd">
<scroll-view scroll-x="true" scroll-with-animation="true" class="scroll-view" :scroll-left="scrollLeft">
<view class="scroll-item" v-for="(item, index) in list" :key="index" @click="changeMenu(index)">
<text class="item-text" :class="curIndex == index? 'active' : ''">{{item.name}}</text>
</view>
</scroll-view>
</view>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: '星期一' },
{ id: 2, name: '星期二' },
{ id: 3, name: '星期三' },
{ id: 4, name: '星期四' },
{ id: 5, name: '星期五' },
{ id: 6, name: '星期六' },
{ id: 7, name: '星期七' },
{ id: 8, name: '星期八' },
{ id: 9, name: '星期九' },
{ id: 10, name: '星期十' }
],
contentScrollW: 0,
curIndex: 0,
scrollLeft: 0,
}
},
mounted() {
this.getScrollW()
},
methods: {
homebtn(){
uni.switchTab({
url: '/pages/index/index'
})
},
yuyuebtn(){
uni.navigateTo({
url: '/pages/yuyue/yuyue'
})
},
getScrollW() {
let query = uni.createSelectorQuery().in(this);
query.select('.scroll-view').boundingClientRect(data => {
this.contentScrollW = data.width
}).exec();
query.selectAll('.scroll-item').boundingClientRect(data => {
let dataLen = data.length;
for (let i = 0; i < dataLen; i++) {
this.list[i].left = data[i].left;
this.list[i].width = data[i].width
}
}).exec()
},
changeMenu(index) {
this.curIndex = index;
this.scrollLeft = this.list[index].left - this.contentScrollW / 2 + this.list[index].width / 2;
},
}
}
</script>
<style lang="scss">
.tabhd{width: 100%;height: 100rpx;box-sizing: border-box;
.scroll-view {height: 100rpx;white-space: nowrap;
.scroll-item {height: 100rpx;padding: 0 20rpx;display: inline-block;text-align: center;
.item-text { font-size: 30rpx;line-height: 100rpx;
&.active {color: #1468FF; }
}
}
}
}
</style>