scroll-view滚动导航自动居中

  =>     

 

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

<!-- enable-flex: 启用 flexbox 布局。开启后,当前节点声明了 `display: flex` 就会成为 flex container,并作用于其孩子节点。 -->
<!-- scroll-with-animation: 在设置滚动条位置时使用动画过渡 -->

<scroll-view class="scroll-list" scroll-x scroll-left="{{scrollLeft}}" scroll-with-animation enable-flex>
    <view class="item {{listIndex==index?'chooseColor':''}}" wx:for="{{10}}" wx:key="index" bindtap="chooseList" data-index="{{index}}">
        {{item}}
    </view>
</scroll-view>
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-list {
  white-space: nowrap;
}
.item{
    width: 230rpx;
    height: 150rpx;
    background: #ccc;
    margin:0 10rpx;
    display: inline-block;
}
.chooseColor{
    background: red;
}

 

scroll-view官方文档:

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

 

注意事项: 在组件中用

wx.createSelectorQuery().select的话, width会获取不到,   参考我的这篇文章:https://www.cnblogs.com/520BigBear/p/17314920.html
posted @ 2023-02-11 14:57  大熊丨rapper  阅读(786)  评论(0)    收藏  举报