微信小程序中点击tab元素使其滚动到容器中间位置

391 阅读1分钟

微信小程序的tab滚动到中间

关于微信小程序在点击tab切换时,将点击的tab元素滚动到容器的中间位置

​ 1.在wxml中使用微信小程序的scroll-view容器,

  ```wxml
  <scroll-view scroll-x="true" scroll-left="{{scrollLeft}}" scroll-with-animation="true">
      <view class="tab-box" style="padding-left:{{rightSpace}}px">
         <view id="{{'item'+item.id}}" class="tab {{currentIndex === index ? 'active'    :''}}" wx:for="{{tabList}}" wx:key="item" data-index="{{index}}" data-id="{{item.id}}" bind:tap="ClickTab">{{item.name}}</view>
      </view>
  </scroll-view>
  ```

​ 2.首先要获取到在点击每一个tab元素时的**offsetLeft**,即点击的tab元素距离设备左边的距离

 ClickTab(e) {
    // console.log(e);
    let index = e.currentTarget.dataset.index
    let id = e.currentTarget.dataset.index + 1
    this.setData({
      currentIndex: index,
      detailId: 'detail' + id,
      itemoffset: e.target.offsetLeft,
    })
    let empty = '#'+'item' +id
    // console.log(empty);
    this.getRect(empty)//在此处调用获取节点信息的函数,并传入元素id
  },

​ 3.再获取到父元素容器的宽度以及点击的那个tab元素的宽度

​ 3.1通过函数封装getRect(ele),ele为上面所传的tab元素id,通过id查询每一个tab元素节点的宽度

 getRect: function (ele) {
    var that = this
    // console.log(ele)
    wx.createSelectorQuery().select('.tab-box').boundingClientRect(res1 => {
      let contentwidth = res1.width //容器宽度
      wx.createSelectorQuery().select(ele).boundingClientRect(res => {
        // console.log(res);
        let itemwidth = res.width / 2   //tab元素宽度的一半
        that.setData({
          scrollLeft: that.data.itemoffset - (contentwidth / 2) + itemwidth//tab元素滚动的距离(滚动至容器中间)
        })
      }).exec()
    }).exec()
  },

​ 4.最后通过微信小程序scroll-view的scroll-let 动态绑定就能够实现点击tab元素滚动到中间

<scroll-view scroll-x="true" scroll-left="{{scrollLeft}}" scroll-with-animation="true">

看最后的效果图,如下

B1E595BDE5B620121035_converted.gif