react 移动端h5 监听滚动document.documentElement.scrollTop取值总取上一次滚动触发结束的值

 react 移动端h5 监听滚动document.documentElement.scrollTop取值总取上一次滚动触发结束的值,也就是上一次滚动到700,这一次滚动到900,那么在touchmove事件回调中打印出的是700

一个不够精确的解决办法是,为处理逻辑增加一个定时器延时获取,给一定的延时,可以获得接近正确的数据,同时又能及时的触发逻辑去渲染UI 

componentDidMount() {
    document.documentElement.addEventListener('touchmove', (e) => {
      this.timer = setTimeout((_) => {
        const postion = this.ScollPostion()
        console.log('滑动距离为:', postion)
        this.setState({ scrollHeight: postion.top })
        clearTimeout(this.timer)
      }, 300)
    })
  }

  ScollPostion = () => {
    var t, l, w, h
    if (document.documentElement && document.documentElement.scrollTop) {
      t = document.documentElement.scrollTop
      l = document.documentElement.scrollLeft
      w = document.documentElement.scrollWidth
      h = document.documentElement.scrollHeight
    } else if (document.body) {
      t = document.body.scrollTop
      l = document.body.scrollLeft
      w = document.body.scrollWidth
      h = document.body.scrollHeight
    }
    return {
      top: t,
      left: l,
      width: w,
      height: h,
    }
  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章