移动端使用jquery实现滚动监听 scrollTop为0可能的原因

当我给html和body设置满屏高度,且在body上监听滚动事件时,在PC上F12调试得到的scrollTop的值是正常的,但是在真机上查看到的 scrollTop值一直为0,我是已经区分了不同浏览器的情况的(如ScollPostion函数)。

如果给document绑定滚动监听,则scrollTop在PC和真机上一直都不触发监听事件,因为scrollTop在两个平台都没有变化,即还是scrollTop=0

如下代码所示:

html,
body {
  overflow-y: auto;
  /* 如果给html或者body设置了高度,会导致在真机上的滚动效果scrollTop一直为0 */
  height: 100vh;
}
$('body').scroll(() => {
      //已经滚动到上面的页面高度
      // var scrollTop = $('body').scrollTop();
      var scrollTop = this.ScollPostion() && this.ScollPostion().top;
      const { top } = this.state;
      const dom = document.getElementsByClassName('navTitle')[0];
      if (scrollTop > top) {
        dom.style.opacity = 1;
      } else {
        dom.style.opacity = 0;
      }
      
      console.log('scrollTop, top', scrollTop, top, this.ScollPostion(), $('body').height());
    });
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,
    }
  }

当我不设置高度

html,
body {
  overflow-y: auto;
  /* 如果给html或者body设置了高度,会导致在真机上的滚动效果scrollTop一直为0 */
  /* height: 100vh; */
}

且监听到body时,body的滚动监听事件并不触发

之后我改为绑定到document,就能同时在真机和PC上触发滚动监听,得到正确的scrollTop了,这是在是很奇怪

作为单页react应用,我给#root节点绑定了监听事件,并且给该root节点设置了height: 100vh,滚动事件也不触发,不知道为什么。。。不过事件总算是解决了 

$(document).scroll(() => {
      //已经滚动到上面的页面高度
      // var scrollTop = $('body').scrollTop();
      var scrollTop = this.ScollPostion() && this.ScollPostion().top;
      const { top } = this.state;
      const dom = document.getElementsByClassName('navTitle')[0];
      if (scrollTop > top) {
        dom.style.opacity = 1;
      } else {
        dom.style.opacity = 0;
      }
      console.log('scrollTop, top', scrollTop, top, this.ScollPostion(), $('body').height());
    });

猜你喜欢

转载自blog.csdn.net/hzxOnlineOk/article/details/107817299