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

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

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


当前回答

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中的解决方案:

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>

这里有一个相当简单的方法

const didScrollToBottom =榆树。滚动顶部+榆树。clientHeight == elm.scrollHeight

例子

elm.onscroll = function() {
    if(elm.scrollTop + elm.clientHeight == elm.scrollHeight) {
        // User has scrolled to the bottom of the element
    }
}

其中elm是从i.e. document.getElementById中检索的元素。

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

Safari可以滚动到导致应用程序错误的页面底部。用>=代替===来解决这个问题。

container.scrollTop >= container.scrollHeight - container.clientHeight

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

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

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