我正在制作一个分页系统(有点像Facebook),当用户滚动到底部时,内容就会加载。我认为最好的方法是找到用户在页面底部的时间,然后运行Ajax查询来加载更多的帖子。
唯一的问题是我不知道如何检查用户是否已经滚动到页面的底部。什么好主意吗?
我使用jQuery,所以请随意提供使用它的答案。
我正在制作一个分页系统(有点像Facebook),当用户滚动到底部时,内容就会加载。我认为最好的方法是找到用户在页面底部的时间,然后运行Ajax查询来加载更多的帖子。
唯一的问题是我不知道如何检查用户是否已经滚动到页面的底部。什么好主意吗?
我使用jQuery,所以请随意提供使用它的答案。
当前回答
如果滚动到底部,请尝试匹配条件
if ($(this)[0].scrollHeight - $(this).scrollTop() ==
$(this).outerHeight()) {
//code for your custom logic
}
其他回答
许多其他解决方案不适合我,因为在滚动到底部我的div触发警报2次,当向上移动时,它也会触发到几个像素,所以解决方案是:
$('#your-div').on('resize scroll', function()
{
if ($(this).scrollTop() +
$(this).innerHeight() >=
$(this)[0].scrollHeight + 10) {
alert('reached bottom!');
}
});
我用这个测试来检测滚动到达底部: event.target.scrollTop === event.target.scrollHeight - event.target.offsetHeight
为了不让尼克的回答反复出现
ScrollActivate();
function ScrollActivate() {
$(window).on("scroll", function () {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
$(window).off("scroll");
alert("near bottom!");
}
});
}
在window上使用.scroll()事件,如下所示:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("bottom!");
}
});
你可以在这里测试它,这取窗口的顶部滚动,所以它向下滚动了多少,添加可见窗口的高度,并检查它是否等于整体内容(文档)的高度。如果你想检查用户是否在底部附近,它看起来像这样:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
alert("near bottom!");
}
});
你可以在这里测试这个版本,只要调整100到你想要触发的底部像素。
所有这些解决方案在Firefox和Chrome上都不适用,所以我使用Miles O'Keefe和meder omuraliev的自定义函数:
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
);
}
function getWindowSize()
{
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
return [myWidth, myHeight];
}
$(window).scroll(function()
{
if($(window).scrollTop() + getWindowSize()[1] == getDocHeight())
{
alert("bottom!");
}
});