说明为什么scrollTop()在这里总是返回0 [英] Explain why scrollTop() always returns 0 here

查看:571
本文介绍了说明为什么scrollTop()在这里总是返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参见 http://codepen.io/anon/pen/NGqPNz

CSS:

html {
  height: 100%;
  overflow-y: hidden;
}
body {
  height: 100%;
  overflow-y: auto;
}

JS:

  $('body').bind("scroll", function () {
    if ($('body').scrollTop()) {
      console.log('triggered!');
    } else {
      console.log($('body').scrollTop());
    }
  });

滚动事件在body元素上触发.滚动条位于body元素上,而不位于html或window元素上.那么,为什么document.body.scrollTop或$('body').scrollTop()返回0?

The scroll event is firing on the body element. The scroll bar is on the body element, not on the html or the window element. So why does document.body.scrollTop or $('body').scrollTop() return 0?

有什么办法可以检测到滚动条的位置吗?或者如果我想使用height,我会卡住:100%;溢出:隐藏在html元素上?

Is there any way I can detect the scroll bar position with this or am I stuck if I want to use height: 100%; overflow:hidden on the html element?

谢谢!

推荐答案

感谢Shikkediel的评论,它似乎是Webkit的错误.如果将div直接放在主体内,然后将scroll事件绑定到div,则它可以工作.

Thanks to Shikkediel's comment, it appears to be a Webkit bug. If you put a div immediately inside the body, and bind the scroll event to the div, it works.

http://codepen.io/anon/pen/bVderq

CSS:

html {
  height: 100%;
  overflow-y: hidden;
}
body {
  height: 100%;
  overflow-y: hidden;
}
.scroll-wrapper {
  height: 100%;
  overflow-y: auto;
}

JS:

$('.scroll-wrapper').bind("scroll", function () {
  if ($('.scroll-wrapper').scrollTop()) {
    console.log('triggered!');
    console.log($('.scroll-wrapper').scrollTop());
  } else {
    console.log($('.scroll-wrapper').scrollTop());
  }
});

这篇关于说明为什么scrollTop()在这里总是返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆