1. 程式人生 > 其它 >導航欄滾動居中

導航欄滾動居中

技術標籤:技術javascript小程式

導航欄滾動居中

在這裡插入圖片描述

wxml

<view class="content">
  <scroll-view scroll-x="true" scroll-with-animation style="width:100%;" class="ul" scroll-left="{{scrollLeft}}">
    <view wx:for="{{8}}" wx:key="index" class="li strategy-tab {{currentIndex == index ? 'active':''}}"
      data-index="{{index}}" catchtap="liClick">可愛{{index}}</view>
  </scroll-view>
</view>

JS

// pages/component/nav/nav.js
Component({
  /**
   * 元件的屬性列表
   */
  properties: {

  },

  /**
   * 元件的初始資料
   */
  data: {
    scrollLeft: 0,
    currentIndex: 0
  },

  /**
   * 元件的方法列表
   */
  methods: {
    liClick(e) {
      let { index } = e.currentTarget.dataset
      let offsetLeft = e.currentTarget.offsetLeft
      this.setData({ currentIndex: index })
      this.playCenter(offsetLeft, index)
    },
    // 點選導航欄滾動
    playCenter(offsetLeft, index) {
      var that = this;
      const winweight = wx.getSystemInfoSync().windowWidth;
      const query = wx.createSelectorQuery().in(this);
      query
        .selectAll(`.strategy-tab`)
        .boundingClientRect(rect => {
          that.setData({
            scrollLeft: offsetLeft - winweight / 2 + rect[index].width / 2
          });
        })
        .exec();
    },
  }
})