How to find out if the user scrolled to the end of

2019-07-13 12:12发布

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

3条回答
家丑人穷心不美
2楼-- · 2019-07-13 12:28
$('#somediv').scrollTop()

will tell you the position from the top

-edit-

$('#somediv').scroll(function(){
    if($('#somediv').scrollTop()==0){
        console.log('top')
    }
})
查看更多
ら.Afraid
3楼-- · 2019-07-13 12:37

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.

查看更多
爷、活的狠高调
4楼-- · 2019-07-13 12:42

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);
});​
查看更多
登录 后发表回答