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

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

但我在这里好像做不到?

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

我该怎么办?


当前回答

只是一个额外的注意在这里,因为我发现这当寻找一个解决方案的固定div,我想滚动。对于我的场景,我发现最好考虑到div上的填充,这样我就可以准确地击中结束。那么扩展@Dr。我将Molle的回答补充如下

$('#flux').bind('scroll', function() {
    var scrollPosition = $(this).scrollTop() + $(this).outerHeight();
    var divTotalHeight = $(this)[0].scrollHeight 
                          + parseInt($(this).css('padding-top'), 10) 
                          + parseInt($(this).css('padding-bottom'), 10)
                          + parseInt($(this).css('border-top-width'), 10)
                          + parseInt($(this).css('border-bottom-width'), 10);

    if( scrollPosition == divTotalHeight )
    {
      alert('end reached');
    }
  });

这将为您提供精确的位置,包括填充和边框

其他回答

虽然这个问题是在5.5年前提出的,但在今天的UI/UX环境中,它仍然非常相关。我想补充一下我的意见。

var element = document.getElementById('flux');
if (element.scrollHeight - element.scrollTop === element.clientHeight)
    {
        // element is at the end of its scroll, load more content
    }

来源:https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight Determine_if_an_element_has_been_totally_scrolled

有些元素不允许滚动元素的整个高度。在这些情况下,你可以使用:

var element = docuement.getElementById('flux');
if (element.offsetHeight + element.scrollTop === element.scrollHeight) {
  // element is at the end of its scroll, load more content
}
$(window).on("scroll", function() {
    //get height of the (browser) window aka viewport
    var scrollHeight = $(document).height();
    // get height of the document 
    var scrollPosition = $(window).height() + $(window).scrollTop();
    if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
        // code to run when scroll to bottom of the page
    }
});

这是github上的代码。

我精心编写了这段代码,用于检测何时滚动到元素的末尾!

let element = $('.element');

if ($(document).scrollTop() > element.offset().top + element.height()) {

     /// do something ///
}

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

$().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()方法是将事件处理程序附加到文档的首选方法。

伙计们,这是缩放问题的解决方案,它适用于所有缩放级别,以防你需要它:

if ( Math.abs(elem.offset().top) + elem.height() + elem.offset().top >= elem.outerHeight() ) {
                    console.log("bottom");
                    // We're at the bottom!
                }
            });
        }