js代码为
Page({data: {items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5','Item 6','Item 7','Item 8','Item 9','Item 10','Item 11','Item 12','Item 13','Item 14','Item 15','Item 16','Item 17','Item 18','Item 19','Item 20','Item 21','Item 22'],scrollLeft: 0,itemView:'item4'},onLoad: function () {this.scrollToPosition(375); },scrollToPosition: function (position) {this.setData({scrollLeft: position});},aaa(e){this.setData({itemView:'item'+e.currentTarget.dataset.index})}
});
wxml代码为
<!-- 根据设定的距离进行滚动 --><scroll-view scroll-x="true" style="white-space: nowrap;height: 200px;" scroll-left="{{scrollLeft}}"><view class="scroll-item" wx:for="{{items}}" wx:for-item="item" id="item{{index}}">{{item}}</view>
</scroll-view><!-- 根据定位的元素进行滚动,会滚动到指定元素(不带动画) -->
<scroll-view scroll-x="true" style="white-space: nowrap;height: 200px;" scroll-into-view="item4"><view class="scroll-item" wx:for="{{items}}" wx:for-item="item" id="item{{index}}">{{item}}</view>
</scroll-view><!-- 根据定位的元素进行滚动,会滚动到指定元素(带动画) -->
<scroll-view scroll-x="true" style="white-space: nowrap;height: 200px;" scroll-into-view="{{itemView}}" scroll-with-animation><view class="scroll-item" wx:for="{{items}}" wx:for-item="item" id="item{{index}}" bind:tap="aaa" data-index="{{index}}">{{item}}</view>
</scroll-view><!-- 设置偏移,例如不想每次都滚动到最前面,比如会将当前选项定位到居中位置 ((小程序宽度/2) - (子元素宽度/2))/2 最后这个除以2是为了转px像素,如本案例 小程序宽度为750rpx,每个item为150rpx,因此偏移值为((750/2)-(150/2))/2 = 150 因此在本案例中是刚好居中定位的-->
<scroll-view scroll-x="true" style="white-space: nowrap;height: 200px;" scroll-into-view="{{itemView}}" scroll-into-view-offset="-150" scroll-with-animation><view class="scroll-item" wx:for="{{items}}" wx:for-item="item" id="item{{index}}" bind:tap="aaa" data-index="{{index}}">{{item}}</view>
</scroll-view>
wxss代码为:
.scroll-item {display: inline-block;padding: 10rpx;width: 150rpx;text-align: center;background-color: #f0f0f0;margin-right: 10rpx;margin-top: 300rpx;
}
scroll-view{width: 750rpx;background-color: pink;
}