实现思路:被选中的 tab
自动滚动到容器中心的效果
<view class="nav">
<scroll-view scroll-x="true" style="max-width: 800rpx;" ref="scrollView" :scroll-left="scrollLeft"
scroll-with-animation>
<view class="tabs">
<section :ref="`tab-${tabIndex}`" :class="['tab-item',current===tabIndex?'active-tab':'']"
@click="scrollToTab(tabIndex)" v-for="(tab,tabIndex) in tabs" :key="tabIndex">
{{tab.name}}
</section>
</view>
</scroll-view>
</view>
scrollToTab(tabIndex) {
this.current = tabIndex; // 更新当前选中的 tab
// 获取 scroll-view 和 tab 的 DOM 元素
const scrollView = this.$refs.scrollView.$el; // uniapp 中需要访问 $el
const tab = this.$refs[`tab-${tabIndex}`][0]; // uniapp 中需要访问 $el
// 计算滚动距离
const scrollViewWidth = scrollView.offsetWidth; // scroll-view 的宽度
const tabOffsetLeft = tab.offsetLeft; // tab 距离左侧的偏移量
const tabWidth = tab.offsetWidth; // tab 的宽度
// 目标滚动位置:将 tab 滚动到中心
const scrollTo = tabOffsetLeft - (scrollViewWidth / 2) + (tabWidth / 2);
this.scrollLeft = scrollTo;
},
.nav {
padding: 0 44rpx;
.tabs {
display: flex;
align-items: center;
white-space: nowrap;
.tab-item {
font-size: 24rpx;
flex: 1;
padding: 8rpx 20rpx;
/* 添加颜色过渡效果 */
}
.active-tab {
border-radius: 40rpx;
background: #7843FF;
}
}
}