1. 程式人生 > >vue利用better-scroll實現通訊錄式列表滾動和左右聯動效果(2)

vue利用better-scroll實現通訊錄式列表滾動和左右聯動效果(2)

3.右邊字母列表滑動或者點選時對應的字母高亮

 _calculateHeight () {
      this.listHeight = []
      const list = this.$refs.listgroup
      let height = 0
      this.listHeight.push(height)
      for (let i = 0; i < list.length; i++) {
        let item = list[i]
        height += item.clientHeight
        this.listHeight.push(height)
      }
    }

watch: {
    data () {
      setTimeout(() => {
        this._calculateHeight()
      }, 20)
    },
    scrollY (newY) {
      const listHeight = this.listHeight
      if (newY > 0) {
        this.currentIndex = 0
        return
      }
      for (let i = 0; i < listHeight.length - 1; i++) {
        const height1 = listHeight[i]
        const height2 = listHeight[i + 1]
        if (-newY >= height1 && -newY < height2) {
          this.currentIndex = i
          return
        }
      }
      this.currentIndex = listHeight.length - 2
    }
  }
 }

(1)監測頁面資料是否接受成功,如果接受成功並渲染則呼叫_calculateHeight計算每一個(列表+標題)的高度,存入在一個數組中。陣列中每一個列表高度是前面所有列表高度的總和。

(2)監測scrollY的變化,滑動的時候scrollY就會發生變化,此時將上一步計算得到的陣列進行遍歷,得到當前列表的高度,和下一個列表的高度,如果srcollY的位置在這兩個位置之間,則設定currentIndex為當前列表的index。在dom中設定current屬性,設定條件判斷當前字母是否應該高亮。判斷條件(:class="{‘current’:currentIndex === index}")