scroll-view滚动导航自动居中
阅读原文时间:2023年07月08日阅读:3

=>   

代码片段:https://developers.weixin.qq.com/s/2fE1QWmE7xFR (复制在微信开发者工具打开)

{{item}}

const app = getApp()

Page({
data: {
listIndex:0, // 当前下标
scrollLeft:null, // 滑动距离
scrollViewWidth:null // scroll-view元素长度
},
onLoad() {
console.log('代码片段是一种迷你、可分享的小程序或小游戏项目,可用于分享小程序和小游戏的开发经验、展示组件和 API 的使用、复现开发问题和 Bug 等。可点击以下链接查看代码片段的详细文档:')
console.log('https://mp.weixin.qq.com/debug/wxadoc/dev/devtools/devtools.html')

wx.createSelectorQuery().select('.scroll-list').boundingClientRect((rect)=>{  
    this.setData({scrollViewWidth:Math.round(rect.width)}) // scroll-view元素长度  
    console.log(rect)  
}).exec()  

},
// 点击
chooseList(e){
console.log(e)
let {index} = e.currentTarget.dataset
let {offsetLeft} = e.currentTarget
this.setData({
listIndex: index,
scrollLeft: offsetLeft - this.data.scrollViewWidth/2
})
},
})

scroll-view官方文档:

https://developers.weixin.qq.com/miniprogram/dev/component/scroll-view.html