小程序scroll-view点击项自动居中

效果

代码

布局样式代码省略,以下只展示逻辑代码

<scroll-view scroll-x scroll-left="{{scrollLeft}}" scroll-with-animation class="scroll-view">
  <view class="class-item" wx:for="{{classList}}" wx:key="id" bindtap="switchClass">
    <text class="name">{{item.className}}</text>
  </view>
</scroll-view>
onReady(){
  wx.createSelectorQuery().select('.scroll-view').boundingClientRect((rect)=>{
    this.data.scrollViewWidth = Math.round(rect.width)
  }).exec()
},
switchClass(){
  let offsetLeft = e.currentTarget.offsetLeft
  this.setData({
    scrollLeft: offsetLeft - this.data.scrollViewWidth/2
  })
}

我们想要的是居中的效果,所以触发滚动的条件是点scroll-view宽度一半之后的项才开始滚动,所以需要减去宽度的一半

offsetLeft为相对于scroll-view总长度的X轴距离,只要相减计算后的数值为正数,就可以证明上面的条件,触发滚动

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现 scroll-view 的无限滚动并且点击居中可以通过以下步骤: 1. 在 scroll-view 中创建一个宽度为所有子元素宽度之和的容器,在容器中使用 flex 布局来排列子元素。 2. 复制一份子元素列表,将其排列在原列表的后面。 3. 监听 scroll-viewscroll 事件,当滚动到最后一个子元素之后,将容器中的子元素列表重置为原列表,然后重新排列子元素。 4. 监听子元素的点击事件,获取被点击的子元素的索引,计算出容器需要滚动的距离,然后使用 scroll-viewscrollIntoView 方法将被点击的子元素滚动到居中位置。 以下是一个简单的示例代码: ```html <scroll-view scroll-x style="white-space: nowrap;" bindscroll="onScroll"> <view wx:for="{{items}}" wx:key="{{index}}" data-index="{{index}}" bindtap="onClick">{{item}}</view> </scroll-view> ``` ```javascript Page({ data: { items: ['A', 'B', 'C', 'D', 'E', 'F', 'G'], containerWidth: 0, itemWidth: 0, currentIndex: 0 }, onLoad: function () { wx.createSelectorQuery().in(this).select('.container').boundingClientRect(res => { this.setData({ containerWidth: res.width }) }).exec() wx.createSelectorQuery().in(this).select('.item').boundingClientRect(res => { this.setData({ itemWidth: res.width }) }).exec() }, onScroll: function (event) { const { scrollLeft } = event.detail const { containerWidth, itemWidth, items } = this.data const maxScrollLeft = (items.length * itemWidth) - containerWidth if (scrollLeft >= maxScrollLeft) { this.setData({ items: [...items, ...items] }) } }, onClick: function (event) { const { index } = event.currentTarget.dataset this.setData({ currentIndex: index }) wx.createSelectorQuery().in(this).select(`.item[data-index="${index}"]`).boundingClientRect(res => { const { containerWidth } = this.data const itemLeft = res.left const itemWidth = res.width const itemCenter = itemLeft + (itemWidth / 2) const scrollLeft = itemCenter - (containerWidth / 2) wx.pageScrollTo({ scrollLeft, duration: 300 }) }).exec() } }) ``` 在这个示例中,我们先获取容器和子元素的宽度,然后在 scroll 事件中判断是否需要重置并重新排列子元素。在点击事件中,我们获取被点击的子元素的位置,然后计算出需要滚动的距离,最后使用 pageScrollTo 方法将 scroll-view 滚动到居中位置。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值