详情页滚动section定位

升学规划小程序(eduPlan),项目详情页:pages/detail/detail
提交记录: 整理详情页
Date:
August 7, 2023 at 11:44:01 GMT+8

效果:

实现思路:

  1. 初始化时候获取各个分组的位置
  2. 在onPageScroll,判断滚动的距离在哪个位置,根据位置设置激活的下标
  3. 展开收起长文本的时候,重新计算各分组的位置

步骤1实现:

  getSectionPositionArr() {
    let arr = []
    const query = wx.createSelectorQuery()
    query.selectAll('.textSectionBox').boundingClientRect()
    query.exec((res) => {
      console.log('检查section位置', res)
      for (var item of res[0]) {
        let top = item.top + this.lastTop - this.data.navH - this.stickHeight
        arr.push(top)
      }
      this.setData({
        positionArr: arr
      })
    })
  },

注意这里lastTop是滚动的距离
步骤2实现:

onPageScroll(e) {
    this.lastTop = e.scrollTop

    this.setData({
      navOpacity: e.scrollTop >= (this.data.topBoxH - this.data.navH - this.stickHeight) ? 1 : 0
    })

    if (this.data.clickSection) {
      return
    }
    this.dealScrollAction(e.scrollTop)
  },


  dealScrollAction(top) {
    let arr = this.data.positionArr
    // 从后往前遍历
    let target = 0
    for (var i = arr.length - 1; i >= 0; i--) {
      let itemTop = arr[i]
      if (parseInt(top) > parseInt(itemTop)) {
        target = i
        break
      }
    }

    this.setData({
      sectionIdx: target
    })
  },

步骤3实现:

  textSectionTap(e) {
    let item = e.currentTarget.dataset.item
    if (item.textFold) { // 超过四行, textFold  1:展开  2:收起  0:少于4行
      item.textFold = item.textFold == 2 ? 1 : 2
      let outidx = e.currentTarget.dataset.outidx
      let idx = e.currentTarget.dataset.idx

      const state = "list[" + outidx + "].item[" + idx + ']'
      this.setData({
        [state]: item //部分刷新  数据
      })
      // 这里重新获取section位置
      this.getSectionPositionArr()
    }
  },

posted on 2023-08-07 11:32  土匪7  阅读(21)  评论(0编辑  收藏  举报