我正在制作一个分页系统(有点像Facebook),当用户滚动到底部时,内容就会加载。我认为最好的方法是找到用户在页面底部的时间,然后运行Ajax查询来加载更多的帖子。
唯一的问题是我不知道如何检查用户是否已经滚动到页面的底部。什么好主意吗?
我使用jQuery,所以请随意提供使用它的答案。
我正在制作一个分页系统(有点像Facebook),当用户滚动到底部时,内容就会加载。我认为最好的方法是找到用户在页面底部的时间,然后运行Ajax查询来加载更多的帖子。
唯一的问题是我不知道如何检查用户是否已经滚动到页面的底部。什么好主意吗?
我使用jQuery,所以请随意提供使用它的答案。
当前回答
我用这个测试来检测滚动到达底部: event.target.scrollTop === event.target.scrollHeight - event.target.offsetHeight
其他回答
这给出了准确的结果,当检查一个可滚动的元素(即不是窗口):
// `element` is a native JS HTMLElement
if ( element.scrollTop == (element.scrollHeight - element.offsetHeight) )
// Element scrolled to bottom
offsetHeight应该给出元素的实际可见高度(包括填充、边距和滚动条),而scrollHeight是元素的整个高度,包括不可见(溢出)区域。
jQuery的.outerHeight()应该给出与JS的.offsetHeight——类似的结果 offsetHeight的MDN文档不清楚它的跨浏览器支持。为了涵盖更多选项,这是更完整的:
var offsetHeight = ( container.offsetHeight ? container.offsetHeight : $(container).outerHeight() );
if ( container.scrollTop == (container.scrollHeight - offsetHeight) ) {
// scrolled to bottom
}
如果滚动到底部,请尝试匹配条件
if ($(this)[0].scrollHeight - $(this).scrollTop() ==
$(this).outerHeight()) {
//code for your custom logic
}
下面是一个使用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 防反跳
尼克回答它的好,但你会有函数,它在滚动时重复自己或将不会工作,如果用户有窗口放大。我想到了一个简单的解决方法只用数学。绕第一个高度,就像假设的那样。
if (Math.round($(window).scrollTop()) + $(window).innerHeight() == $(document).height()){
loadPagination();
$(".go-up").css("display","block").show("slow");
}
显然,对我有用的是“身体”,而不是像这样的“窗口”:
$('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
}
});