scroll-view 横向滚动指定位置

<template>
	<view>
		<view class="scrBox">
			<scroll-view class="menu-list" :scroll-into-view="goIndex" scroll-x="true">
				<view v-for="(item,k) in timeList" :key="k" :id='"id" + k' @tap="sel(k,item)" class="ListBox">
					<view class="rush" :class="{'curBac':item.id==curId}">{{item.name}}</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default{
		data(){
			return{
				curId:0,
				goIndex:"",
				timeList:[
					{
						name:"陈浩南",
						id:0
					},
					{
						name:"山鸡",
						id:1
					},
					{
						name:"包达二",
						id:2
					},
					{
						name:"包达明",
						id:3
					},
					{
						name:"梁二",
						id:4
					},
					{
						name:"柯志华",
						id:5
					},
					{
						name:"苏阿细",
						id:6
					},
					{
						name:"十三妹",
						id:7
					},
					{
						name:"丁瑶",
						id:8
					},
					{
						name:"kk",
						id:9
					},
					{
						name:"林淑芬",
						id:10
					},
					{
						name:"靓坤",
						id:11
					}
				]
			}
		},
		methods:{
			sel(index,item){
				this.goIndex = "id" + index
				this.curId = item.id
			}
		}
	}
</script>

<style lang="scss">
	.scrBox{
		width: 100%;
		height: 120rpx;
		white-space: nowrap;
		.menu-list {
			.ListBox {
				display: inline-block;
				font-size: 24rpx;
				color: #333;
				text-align: center;
				width: 115rpx;
			}
			.rush{
				font-size: 21rpx;
				color: #999;
				margin: 0 auto;
			}
			.curBac{
				width: 88rpx;
				line-height: 30rpx;
				background: #00AFFF;
				border-radius: 15rpx;
				color: #fff;
			}
		}
	}
</style>

Tips:

  1. scroll-view的外层view需要white-space: nowrap使得内部组件不换行
  2. scroll-view的内层view需要display: inline-block使得内部组件横向排列
  3. scroll-into-view值应为某子元素id(id不能以数字开头)
### 实现 `scroll-view` 组件中的横向滚动与元素定位 为了使 `scroll-view` 支持横向滚动,必须为其设定固定的宽度,并通过设置 `scroll-x="true"` 属性来启用该功能[^1]。对于想要实现平滑滚动至特定子节点的情况,则可以利用 `scroll-into-view` 属性配合目标节点的 ID 来达成目的。 下面是一个简单的例子展示如何配置这些属性: ```html <view class="container"> <!-- 设置 scroll-x=true 开启水平滚动 --> <scroll-view id="scrollView" scroll-x="true" bindscrolltolower="lower" lower-threshold="50" scroll-with-animation="{{true}}" scroll-left="{{currentLeft}}" style="width: 750rpx; white-space: nowrap;"> <!-- 子项列表 --> <block wx:for="{{items}}" wx:key="id"> <view id="{{item.id}}" class="child-item">{{item.text}}</view> </block> </scroll-view> </view> ``` 当需要让某个具体项目进入视图中央时,在 JavaScript 中更新对应的 `scroll-into-view` 值即可: ```javascript Page({ data: { currentId: '' }, scrollToItem(e) { const { id } = e.currentTarget.dataset; this.setData({ 'currentId': '#' + id }); } }) ``` 同时需要注意的是,如果希望在页面初次加载或者某些条件下自动滚到某位置,可以在合适时机调用 setData 方法改变 `scroll-into-view` 的值从而触发滚动行为。 另外,关于样式方面的问题,比如 Flexbox 不起作用的现象可能是由于容器本身没有足够的空间容纳所有子元素造成的;因此建议确保父级有足够的尺寸以适应内部内容的需求[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值