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

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

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


当前回答

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

// `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
}

其他回答

在window上使用.scroll()事件,如下所示:

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       alert("bottom!");
   }
});

你可以在这里测试它,这取窗口的顶部滚动,所以它向下滚动了多少,添加可见窗口的高度,并检查它是否等于整体内容(文档)的高度。如果你想检查用户是否在底部附近,它看起来像这样:

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
       alert("near bottom!");
   }
});

你可以在这里测试这个版本,只要调整100到你想要触发的底部像素。

如果有人想要一个香草的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 });

下面是最简单的方法:

const handleScroll = () => {
if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight) {
   console.log('scrolled to the bottom')
}}

window.addEventListener('scroll', handleScroll)

(2021) 这里的很多答案都涉及到一个元素的引用,但如果你只关心整个页面,只需使用:

function isBottom() {
  const { scrollHeight, scrollTop, clientHeight } = document.documentElement;
  const distanceFromBottom = scrollHeight - scrollTop - clientHeight;
  return distanceFromBottom < 20; // adjust the number 20 yourself
}

为了不让尼克的回答反复出现

ScrollActivate();

function ScrollActivate() {
    $(window).on("scroll", function () {
        if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
            $(window).off("scroll");
            alert("near bottom!");
        }
    });
}