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

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

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


当前回答

我在纯js中的解决方案:

let el=document.getElementById('el'); el.addEventListener('scroll', function(e) { if (this.scrollHeight - this.scrollTop - this.clientHeight<=0) { 警报(“底部”); } }); #el{ 宽度:400px; 高度:100px; 溢出-y:滚动; } <div id=“el”> <div>内容</div> <div>内容</div> <div>内容</div> <div>内容</div> <div>内容</div> <div>内容</div> <div>内容</div> <div>内容</div> <div>内容</div> <div>内容</div> <div>内容</div> </div>

其他回答

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

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

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

Nick Craver的回答需要稍作修改,以适应iOS 6 Safari Mobile,应该是:

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

将$(window).height()更改为window。innerHeight应该这样做,因为当地址栏被隐藏时,一个额外的60px被添加到窗口的高度,但使用$(window).height()不会反映这个变化,而使用window。innerHeight。

注:窗口。innerHeight属性还包括水平滚动条的高度(如果它被渲染),不像$(window).height()不包括水平滚动条的高度。这在Mobile Safari中不是问题,但在其他浏览器或未来版本的Mobile Safari中可能会导致意想不到的行为。将==更改为>=可以修复大多数常见用例的这个问题。

阅读更多关于窗户的内容。这里的innerHeight属性

如果你调用$(window).height() Chrome会给出页面的全部高度

相反,使用window。innerHeight来检索窗口的高度。 必要的检查应包括:

if($(window).scrollTop() + window.innerHeight > $(document).height() - 50) {
    console.log("reached bottom!");
}

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

ScrollActivate();

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