我有一个div框(称为flux),里面有可变数量的内容。 此divbox已将溢出设置为自动。

现在,我要做的是,当使用滚动到这个div框的底部,加载更多的内容到页面,我知道如何做到这一点(加载内容),但我不知道如何检测当用户已经滚动到div标签的底部? 如果我想对整个页面都这样做,我将使用。scrolltop并从。height中减去它。

但我在这里好像做不到?

我已经尝试从通量。scrolltop,然后包装内的所有内容在一个div称为内部,但如果我采取通量的innerHeight它返回564px (div被设置为500作为高度)和“内部”的高度它返回1064,而滚动顶部,当在div的底部说564。

我该怎么办?


当前回答

没有一个答案对我有用,但这个答案对我有用:

$(window).on('scroll', function() {
    if ($(window).scrollTop() >= $('#flux').offset().top + $('#flux').outerHeight() - window.innerHeight) {
        alert('You reached the end of the DIV');
    }
});

其他回答

你可以使用一些属性/方法:

$().scrollTop()//how much has been scrolled
$().innerHeight()// inner height of the element
DOMElement.scrollHeight//height of the content of the element

所以你可以取前两个属性的和,当它等于最后一个属性时,你就到了终点:

jQuery(function($) {
    $('#flux').on('scroll', function() {
        if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
            alert('end reached');
        }
    })
});

http://jsfiddle.net/doktormolle/w7X9N/

编辑:我已经更新了'绑定'到'上'按:

从jQuery 1.7开始,.on()方法是将事件处理程序附加到文档的首选方法。

如果你没有使用Math.round()函数,Dr.Molle建议的解决方案在某些情况下当浏览器窗口有缩放时将不起作用。

例如 $(this).scrollTop() + $(this).innerHeight() = 600

(美元)[0]。scrollHeight yield = 599.99998

600 >= 599.99998失败。

下面是正确的代码:

jQuery(function($) {
    $('#flux').on('scroll', function() {
        if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10)) {
            alert('end reached');
        }
    })
});

如果你不需要一个严格的条件,你也可以添加一些额外的边缘像素

var margin = 4

jQuery(function($) {
    $('#flux').on('scroll', function() {
        if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10) - margin) {
            alert('end reached');
        }
    })
});

不确定是否有任何帮助,但这就是我的做法。

我有一个比窗口大的索引面板,我让它滚动,直到达到这个索引。然后我把它固定好。一旦你滚动到页面顶部,这个过程就反过来了。

的问候。

<style type="text/css">
    .fixed_Bot {    
            position: fixed;     
            bottom: 24px;    
        }     
</style>

<script type="text/javascript">
    $(document).ready(function () {
        var sidebarheight = $('#index').height();
        var windowheight = $(window).height();


        $(window).scroll(function () {
            var scrollTop = $(window).scrollTop();

            if (scrollTop >= sidebarheight - windowheight){
                $('#index').addClass('fixed_Bot');
            }
            else {
                $('#index').removeClass('fixed_Bot');
            }                   
        });
    });

</script>

如果你需要在一个隐藏了overflow-y或滚动的div上使用它,像这样的东西可能就是你需要的。

if ($('#element').prop('scrollHeight') - $('#element').scrollTop() <= Math.ceil($('#element').height())) {
    at_bottom = true;
}

我发现celll是需要的,因为prop scrollHeight似乎是圆的,或者可能是其他原因导致这是由小于1。

如果有人得到scrollHeight为undefined,则选择元素的第一个子元素:mob_top_menu[0].scrollHeight