微信小程序(uniApp):scroll-view横向滚动实现点击元素滚动到页面中间的效果

wxml:

<scroll-view
	class="scroll"
	scroll-x='true'
	scroll-with-animation
	:scroll-left='scrollLeft'>
	<view 
		v-for="(item, index) in tabsList" :key='item.id'
		:class="[{active: currentIndex === index }, 'scroll-item']"
		@click="changeTab(index)">
	{{item.name}}
	</view>
</scroll-view>

wxss:

.scroll{
	width: 100%;
	white-space: nowrap;
	view{
		display: inline-block;
		font-size: 30upx;
		font-weight: 400;
		line-height: 42upx;
		padding: 18upx 30upx;
		color: #000;
		position: relative;
		&.active{
			font-size: 36upx;
			font-weight: 800;
			line-height: 50upx;
		}
		&.active::after{
			content: '';
			display: block;
			width: 100%;
			border-left: 30upx solid #fff;
			border-right: 30upx solid #fff;
			box-sizing: border-box;
			height: 19upx;
			position: absolute;
			left: 0;
			bottom: 19upx;
			background: #FFC385;
			z-index: -1;
		}
	}
}

js(重点部分)

// 切换当前Tab
changeTab(index){
	this.$emit('changeTab', index)
	this.moveTo(index)
},
// 将点击元素移动到中间
moveTo(index) { 
	const query = uni.createSelectorQuery().in(this)
	query
		.selectAll(`.scroll-item`)
		.boundingClientRect(rect => {
			const windowWidth = this.$store.state.windowWidth			// 屏幕宽度
			let width = 0
			// 循环获取计算当前点击的标签项距离左侧的距离
			for (let i = 0; i < index; i++) {
				width += rect[i].width
			}
			// 当大于屏幕一半的宽度则滚动,否则就设置位置为0
			if (width > windowWidth / 2) {
				this.scrollLeft = width + rect[index].width / 2 - windowWidth / 2
			} else {
				this.scrollLeft = 0
			}
	}).exec()
},
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值