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

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

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


当前回答

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

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

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

其他回答

下面是一个使用es6和debounce的JavaScript解决方案:

document.addEventListener('scroll', debounce(() => {
  if(document.documentElement.scrollHeight === window.pageYOffset + window.innerHeight) {
    // Do something
  }
}, 500))

function debounce(e,t=300){let u;return(...i)=>{clearTimeout(u),u=setTimeout(()=>{e.apply(this,i)},t)}}

演示:https://jsbin.com/jicikaruta/1/edit?js,输出

引用:

scrollHeight pageYOffset innerHeight 防反跳

让我展示不使用JQuery的方法。简单的JS函数:

function isVisible(elem) {
  var coords = elem.getBoundingClientRect();
  var topVisible = coords.top > 0 && coords.top < 0;
  var bottomVisible = coords.bottom < shift && coords.bottom > 0;
  return topVisible || bottomVisible;
}

简短的例子如何使用它:

var img = document.getElementById("pic1");
    if (isVisible(img)) { img.style.opacity = "1.00";  }

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!");
       }
   });

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属性

我已经用纯JS做了这个非常简单的方法。

function onScroll() {    
    if (window.pageYOffset + window.innerHeight >= document.documentElement.scrollHeight - 50) {
        Console.log('Reached bottom')
    }
}
window.addEventListener("scroll", onScroll);