微信小程序横滑定位元素案例代码

js代码为

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); // 假设我们要滚动到375px的位置
  },

  scrollToPosition: function (position) {
    this.setData({
      scrollLeft: position
    });
  },
  aaa(e){
    this.setData({
      itemView:'item'+e.currentTarget.dataset.index
    })
  }
});

wxml代码为

js 复制代码
<!-- 根据设定的距离进行滚动 -->

<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代码为:

css 复制代码
.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;
}
相关推荐
speedoooo2 小时前
在现有App里嵌入一个AI协作者
前端·ui·小程序·前端框架·web app
万岳科技系统开发9 小时前
私域直播小程序源码的整体架构设计与实现思路
学习·小程序
ee82ee10 小时前
uniapp小程序底部键盘唤起问题处理,包含间隙处理,动画处理
微信小程序
qq_124987075311 小时前
基于springboot健康养老APP的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·mysql·微信小程序·毕业设计
汤姆yu11 小时前
基于微信小程序的驾校预约与学习系统
学习·小程序·驾校预约
夏源11 小时前
【微信小程序】实现引入 Echarts 并实现更新数据
微信小程序
speedoooo12 小时前
未来的App不再需要菜单栏?
前端·ui·容器·小程序·web app
猿究院_xyz13 小时前
微信小程序与echarts联动安卓真机测试出现黑色阴影
前端·javascript·微信小程序·小程序·echarts
说私域14 小时前
不同类型企业构建私域流量的必要性及定制开发AI智能名片商城小程序的应用
大数据·人工智能·小程序
老华带你飞15 小时前
健身房预约|基于springboot 健身房预约小程序系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·小程序