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

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

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


当前回答

您可以尝试以下代码,

$("#dashboard-scroll").scroll(function(){
    var ele = document.getElementById('dashboard-scroll');
    if(ele.scrollHeight - ele.scrollTop === ele.clientHeight){
       console.log('at the bottom of the scroll');
    }
});

其他回答

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

ScrollActivate();

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

Nick Craver的回答很好,避免了$(document).height()的值因浏览器而异的问题。

为了让它在所有浏览器上都能工作,使用James Padolsey的这个函数:

function getDocHeight() {
    var D = document;
    return Math.max(
        D.body.scrollHeight, D.documentElement.scrollHeight,
        D.body.offsetHeight, D.documentElement.offsetHeight,
        D.body.clientHeight, D.documentElement.clientHeight
    );
}

代替$(document).height(),这样最终的代码是:

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

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

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

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

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

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

显然,对我有用的是“身体”,而不是像这样的“窗口”:

$('body').scroll(function() {


 if($('body').scrollTop() + $('body').height() == $(document).height()) {
     //alert at buttom
 }
 });

为了实现跨浏览器兼容性:

  function getheight(){
    var doc = document;
    return  Math.max(
        doc.body.scrollHeight, doc.documentElement.scrollHeight,
        doc.body.offsetHeight, doc.documentElement.offsetHeight,
        doc.body.clientHeight, doc.documentElement.clientHeight

        );
   }

然后调用函数getheight()而不是$(document).height()

$('body').scroll(function() {


   if($('body').scrollTop() + $('body').height() == getheight()  ) {
     //alert at bottom
 }
});

接近底部使用:

$('body').scroll(function() {


if($('body').scrollTop() + $('body').height() > getheight() -100 ) {
    //alert near bottom
 }
 });