手写tabs切换

实现思路:被选中的 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;
				}
			}
		}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值