如何确定用户是否使用jQuery滚动到HTML容器的末尾?

时间:2012-08-23 14:51:03

标签: javascript jquery html css scroll

如何确定用户是否在可滚动容器中向上滚动或向下滚动?

jQuery是否提供任何机制?

的CSS:

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

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

非常感谢!

专利

3 个答案:

答案 0 :(得分:3)

$('#somediv').scrollTop()

会告诉你顶部的位置

-edit -

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

答案 1 :(得分:2)

是的,您可以访问可滚动容器的当前scroll top值。

Here working is jsFiddle.

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

答案 2 :(得分:1)

您可以测试滚动位置by comparing 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
此示例保留了div边距顶部和底部的5个像素。