Scroll listener on body

2019-02-18 00:50发布

I would like to ask about scroll listener. I want to add scroll listener on body but it seems doesnt work.

$('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...

3条回答
迷人小祖宗
2楼-- · 2019-02-18 00:59

Because the body isn't scrolling, the window is.

In This example, you'll see that the event listener bound to the parent container is what's firing, because that element is the one that's actually scrolling.

The HTML looks like this:

<div id="container">
    <p id="content">some text</p>
</div>

The CSS looks like this:

#container {
    height: 200px;
    overflow-y: scroll;
}

#content {
    height: 1000px;
}

And the relevant JS looks like this:

$('#container').on('scroll', function() {
    console.log('#container');
});

$('#content').on('scroll', function() {
    console.log('#content');
});
查看更多
祖国的老花朵
3楼-- · 2019-02-18 01:00

Try with:

$(window).scroll(function(){
  console.log('SCROLL BODY');
});

This should be supported by all browsers.

查看更多
等我变得足够好
4楼-- · 2019-02-18 01:06

All the answers above expect jQuery being the framework of use. A framework agnostic / plain JS implementation could look like this

ES 5:

// ES 5 :
document.getElementsByTagName('body')[0].onscroll = function() {
    console.log("scrolling");
};

ES 6 (and above) :

// ES 6 (and above)
document.getElementsByTagName('body')[0].onscroll = () => {
    console.log("scrolling");
};

查看更多
登录 后发表回答