小程序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軸距離,只要相減計算后的數值為正數,就可以證明上面的條件,觸發滾動


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM