scroll-view | 微信开放文档scroll-view | 微信开放文档效果代码布局样式代码省略,以下只展示逻辑代码



{{item.className}}


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
})
}



{{item.className}}


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宽度一半之后的项才开始滚动,所以需要减去宽度的一半scroll-viewoffsetLeft为相对于scroll-view总长度的X轴距离,只要相减计算后的数值为正数,就可以证明上面的条件,触发滚动offsetLeftscroll-view推荐阅读:微信小程序 scroll-view实现锚点滑动的示例微信小程序 scroll-view实现锚点滑动的示例总结总结总结