我正在制作一个分页系统(有点像Facebook),当用户滚动到底部时,内容就会加载。我认为最好的方法是找到用户在页面底部的时间,然后运行Ajax查询来加载更多的帖子。

唯一的问题是我不知道如何检查用户是否已经滚动到页面的底部。什么好主意吗?

我使用jQuery,所以请随意提供使用它的答案。


当前回答

许多其他解决方案不适合我,因为在滚动到底部我的div触发警报2次,当向上移动时,它也会触发到几个像素,所以解决方案是:

        $('#your-div').on('resize scroll', function()
        {
            if ($(this).scrollTop() +
                $(this).innerHeight() >=
                $(this)[0].scrollHeight + 10) {

                alert('reached bottom!');
            }
        });

其他回答

请检查这个答案

 window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
       console.log("bottom");
    }
};

你可以执行footerHeight - document.body.offsetHeight来查看你是否接近页脚或到达页脚

这是我的意见,因为公认的答案对我不起作用。

var documentAtBottom = (document.documentElement.scrollTop + window.innerHeight) >= document.documentElement.scrollHeight;

这给出了准确的结果,当检查一个可滚动的元素(即不是窗口):

// `element` is a native JS HTMLElement
if ( element.scrollTop == (element.scrollHeight - element.offsetHeight) )
    // Element scrolled to bottom

offsetHeight应该给出元素的实际可见高度(包括填充、边距和滚动条),而scrollHeight是元素的整个高度,包括不可见(溢出)区域。

jQuery的.outerHeight()应该给出与JS的.offsetHeight——类似的结果 offsetHeight的MDN文档不清楚它的跨浏览器支持。为了涵盖更多选项,这是更完整的:

var offsetHeight = ( container.offsetHeight ? container.offsetHeight : $(container).outerHeight() );
if  ( container.scrollTop == (container.scrollHeight - offsetHeight) ) {
   // scrolled to bottom
}

我用这个测试来检测滚动到达底部: event.target.scrollTop === event.target.scrollHeight - event.target.offsetHeight

如果有人想要一个香草的JavaScript解决方案,需要检测当用户滚动到<div>的底部时,我设法通过使用这些代码行实现它

window.addEventListener("scroll", () => {
    var offset = element.getBoundingClientRect().top - element.offsetParent.getBoundingClientRect().top;
    const top = window.pageYOffset + window.innerHeight - offset;

    if (top === element.scrollHeight) {
        console.log("bottom");
    }
}, { passive: false });