我正在制作一个分页系统(有点像Facebook),当用户滚动到底部时,内容就会加载。我认为最好的方法是找到用户在页面底部的时间,然后运行Ajax查询来加载更多的帖子。
唯一的问题是我不知道如何检查用户是否已经滚动到页面的底部。什么好主意吗?
我使用jQuery,所以请随意提供使用它的答案。
我正在制作一个分页系统(有点像Facebook),当用户滚动到底部时,内容就会加载。我认为最好的方法是找到用户在页面底部的时间,然后运行Ajax查询来加载更多的帖子。
唯一的问题是我不知道如何检查用户是否已经滚动到页面的底部。什么好主意吗?
我使用jQuery,所以请随意提供使用它的答案。
当前回答
var elemScrolPosition = elem.scrollHeight - elem.scrollTop - elem.clientHeight;
它计算滚动条到元素底部的距离。 等于0,如果滚动条已经到达底部。
其他回答
您可以尝试以下代码,
$("#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');
}
});
(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属性
根据Nick Craver的回答,你可以限制滚动事件,这样它就不会频繁地触发,从而提高浏览器性能:
var _throttleTimer = null;
var _throttleDelay = 100;
var $window = $(window);
var $document = $(document);
$document.ready(function () {
$window
.off('scroll', ScrollHandler)
.on('scroll', ScrollHandler);
});
function ScrollHandler(e) {
//throttle event:
clearTimeout(_throttleTimer);
_throttleTimer = setTimeout(function () {
console.log('scroll');
//do work
if ($window.scrollTop() + $window.height() > $document.height() - 100) {
alert("near bottom!");
}
}, _throttleDelay);
}
Safari可以滚动到导致应用程序错误的页面底部。用>=代替===来解决这个问题。
container.scrollTop >= container.scrollHeight - container.clientHeight