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,
    }
  }

 

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