Javascript 在身体上滚动侦听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25951121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scroll listener on body
提问by user1297783
I would like to ask about scroll listener. I want to add scroll listener on body but it seems doesnt work.
我想问一下滚动监听器。我想在 body 上添加滚动侦听器,但似乎不起作用。
$('body').scroll(function(){
console.log('SCROLL BODY');
});
I create basic example on fiddle, can someone explain me why it doesn't to work? Sorry for nubies question...
我在fiddle上创建了基本示例,有人能解释一下为什么它不起作用吗?对不起nubies的问题...
回答by Lorenzo Marcon
Try with:
尝试:
$(window).scroll(function(){
console.log('SCROLL BODY');
});
This should be supported by all browsers.
这应该被所有浏览器支持。
回答by mareks
All the answers above expect jQuery being the framework of use. A framework agnostic / plain JS implementation could look like this
上面的所有答案都希望 jQuery 成为使用框架。一个框架不可知/纯 JS 实现可能看起来像这样
ES 5:
ES 5:
// ES 5 :
document.getElementsByTagName('body')[0].onscroll = function() {
console.log("scrolling");
};
ES 6 (and above) :
ES 6(及以上):
// ES 6 (and above)
document.getElementsByTagName('body')[0].onscroll = () => {
console.log("scrolling");
};
回答by Robert
Because the body isn't scrolling, the windowis.
因为身体没有滚动,所以window是。
In This example, you'll see that the event listener bound to the parent containeris what's firing, because that element is the one that's actually scrolling.
在此示例中,您将看到绑定到父级的事件侦听器container正在触发,因为该元素是实际滚动的元素。
The HTML looks like this:
HTML 如下所示:
<div id="container">
<p id="content">some text</p>
</div>
The CSS looks like this:
CSS 看起来像这样:
#container {
height: 200px;
overflow-y: scroll;
}
#content {
height: 1000px;
}
And the relevant JS looks like this:
相关的 JS 如下所示:
$('#container').on('scroll', function() {
console.log('#container');
});
$('#content').on('scroll', function() {
console.log('#content');
});
回答by Pierre Dunn
The Pure JS Solution
纯 JS 解决方案
Everything is very simple: just use addEventListenerfor scrolling event.
一切都很简单:只addEventListener用于滚动事件。
document.body.addEventListener('scroll', function( event ) {
console.log(';{};');
} );
And make bodyscrollable with CSS:
并body使用 CSS使其可滚动:
:root {
overflow: hidden;
}
body {
overflow-y: scroll;
max-height: 100vh;
}
I do not know why simple handler assignment doesn't work. If you know why — please, tell me.
我不知道为什么简单的处理程序分配不起作用。如果你知道为什么——请告诉我。
document.body.onscroll = function( event ) {
console.log('You will never see this message.');
};
Also you could do this:
你也可以这样做:
document.body.onwheel = function( e ) {
...
};
This event will be triggered only when you using a wheel (for me that wasn't obvious, actually), so if you will scroll your page with a scrollbar it will not trigger.
只有在您使用滚轮时才会触发此事件(对我来说实际上并不明显),因此如果您使用滚动条滚动页面,它将不会触发。

