小程序scroll-view自动居中 微信小程序scroll-view点击项自动居中效果的实现

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

小程序scroll-view自动居中 微信小程序scroll-view点击项自动居中效果的实现

WahFung   2021-04-21 我要评论

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轴距离,只要相减计算后的数值为正数,就可以证明上面的条件,触发滚动

推荐阅读:微信小程序 scroll-view实现锚点滑动的示例

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们