这个方法是在百度借鉴的,
原文章地址:https://www.cnblogs.com/langxiyu/p/13159055.html
原文章中有三种方法(居左、居左留一、居中),我在这里只记录一个居中显示的方法
<template>
<view class="home">
<scroll-view class="content-scroll" scroll-x @scroll="scroll" :scroll-left="scrollLeft" scroll-with-animation style="white-space: nowrap;height: 80rpx;">
<view class="item scroll-item" style="height:80rpx;display: inline-block;" v-for="(item, index) in navList" :key="index">
<view class="flex flex-column align-center " @click="changeItem(index)">
<view class="thname" :class="currentIndex == index ? 'act-nav':''">{{ item.name }}</view>
</view>
</view>
</scroll-view>
</view>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
navList: [{
name: '精选'
},
{
name: '语言课程'
},
{
name: '名师录播课'
},
{
name: '优选直播课'
},
{
name: '定制化培训'
},
{
name: '夏冬令营'
},
{
name: '少儿多语种'
},
{
name: '测试中心'
},
{
name: '客户端下载'
},
{
name: '关于我们'
}
],
contentScrollW: 0, // 导航区宽度
curIndex: 0, // 当前选中
scrollLeft: 0, // 横向滚动条位置
}
},
mounted() {
// 获取标题区域宽度,和每个子元素节点的宽度
this.getScrollW()
},
methods: {
// 获取标题区域宽度,和每个子元素节点的宽度以及元素距离左边栏的距离
getScrollW() {
const query = uni.createSelectorQuery().in(this);
query.select('.content-scroll').boundingClientRect(data => {
// 拿到 scroll-view 组件宽度
this.contentScrollW = data.width
}).exec();
query.selectAll('.scroll-item').boundingClientRect(data => {
let dataLen = data.length;
for (let i = 0; i < dataLen; i++) {
// scroll-view 子元素组件距离左边栏的距离
this.navList[i].left = data[i].left;
// scroll-view 子元素组件宽度
this.navList[i].width = data[i].width
}
}).exec()
},
changeItem(index) {
this.currentIndex = index
console.log(this.currentIndex)
this.scrollLeft = this.navList[index].left - this.contentScrollW / 2 + this.navList[index].width / 2;
},
}
}
</script>