How to find out if the user scrolled to the end of a HTML container with jQuery?

孤街醉人 提交于 2020-01-14 14:42:08

问题


how do I find out if the user scrolled up to the top or down to the bottom in a scrollable container?

Does jQuery offer any mechanisms?

css:

#container {
    display: block;
    width: 250px;
    height: 25px;
    background: green;
}
#scrolling {
    width: 250px;
    height: 300px;
    backround: red;
    overflow: auto;
}

http://jsfiddle.net/Hmaf2/2/

Thanks a lot!

Pat


回答1:


You can test the scroll position by comparing the height, scrollable height and scroll offset of the div:

$(document).ready(function(){
    $('#scrolling').scroll(function(){
        var scrollTop = $(this).scrollTop();
        var iheight = $(this).innerHeight();
        var sheight = this.scrollHeight;
        var text = '';
        if (scrollTop <= 5) {
            text = 'top';
        }
        else if (scrollTop+5 >= sheight-iheight) {
            text = 'bottom';
        }
        else {
            text = scrollTop+' middle ('+iheight+','+sheight+')';
        }
        $('#result').text(text);
    });
});

fiddle
This example has reserved 5 pixels from the top and bottom of the div's margin.




回答2:


$('#somediv').scrollTop()

will tell you the position from the top

-edit-

$('#somediv').scroll(function(){
    if($('#somediv').scrollTop()==0){
        console.log('top')
    }
})



回答3:


Yes you can access the current scroll top value of a scrollable container.

Here working is jsFiddle.

$('#scrolling').scroll(function() {
   var scrollTop = $(this).scrollTop();
   console.log(scrollTop);
});​


来源:https://stackoverflow.com/questions/12094421/how-to-find-out-if-the-user-scrolled-to-the-end-of-a-html-container-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!