小程序導航欄選擇每一項居中(scroll-view)

前言

在項目中遇到點擊scroll-view中每一項使其居中,查看文檔後發現有scroll-view有屬性scroll-into-view能夠根據id來定位每一項,可是沒法居中,因而我想到了使用scroll-left來計算滾動距離是使一項居中.函數

查看效果


完成思路


  1. 獲取屏幕寬度的一半(srceenHalfWidth)
  2. 獲取元素寬度的一半(即subHalfWidth)
  3. 獲取元素到手機屏幕左邊的距離(即元素的subLeft)
  4. 計算scroll-view須要滾動的距離:needScroll = subLeft - srceenHalfWidth + subHalfWidth
  5. 監聽scroll-view滾動獲取上次滾動的距離(prevDistance)
  6. 計算scroll-left屬性的值 scroll-left= needScroll + prevDistance

wxml代碼

<scroll-view class="power-view" scroll-x="true" scroll-with-animation="true" scroll-left="{{scrollLeft}}" bindscroll="scrollMove">
    <block wx:for="{{powerList}}" wx:key>

        <view class="item {{index == activeIdx?'active':''}}" bindtap="chooseSub" id="v{{index}}" data-index="{{index}}">
          <view class="icon"></view>
          <view class="text">整年海量優惠</view>
        </view>

    </block>

  </scroll-view>複製代碼

js代碼

data: {
    powerList: ['v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v9', 'v10', 'v11', 'v12'],
    activeIdx: 0, //選中的index
  },

  /**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function (options) {

    let scrollInfo = {
      prevDistance: 0, //滾動條的距離(默認爲0)
      screenHalfwidth: wx.getSystemInfoSync().windowWidth / 2, 
    }

    this.data.scrollInfo = scrollInfo; 

  },

  //選擇某一項類目
  chooseSub: function(e) {

    let index = e.currentTarget.dataset.index;

    this.setData({
      activeIdx: index
    })
    this.getRect(index);
  },

  //獲取類目的寬高
  getRect: function (index) {

    let that = this;
    let query = wx.createSelectorQuery();
    query.select("#v" + index).boundingClientRect(function (rect) {

      that.data.scrollInfo.subLeft = rect.left; //元素一半寬度
      that.data.scrollInfo.subHalfWidth = rect.width / 2; 

      that.moveTo();
    }).exec()

  },

  //移動導航欄
  moveTo: function() {
    let subLeft = this.data.scrollInfo.subLeft;
    let subHalfWidth = this.data.scrollInfo.subHalfWidth;
    let prevDistance = this.data.scrollInfo.prevDistance;
    let screenHalfwidth = this.data.scrollInfo.screenHalfwidth;

    let needScroll = subLeft - screenHalfwidth + subHalfWidth;
    let scrollLeft = needScroll + prevDistance;

    this.setData({
      scrollLeft: scrollLeft
    })
  },

  //記錄滾動的距離
  scrollMove: function(e) {

    let distance = e.detail.scrollLeft;
    this.data.scrollInfo.prevDistance = distance
  },複製代碼

結尾

有兩種特殊狀況this

  1. 當scroll-left < 0,scroll-view會滾動到 scroll-left = 0;
  2. 當scroll-left > maxScroll,scroll-view會滾動到 scroll-left = maxScroll;

因此仍是正常運行.spa

相關文章
相關標籤/搜索