【发布时间】:2021-09-23 13:31:06
【问题描述】:
有没有办法使用 Jquery 找出页面结束,以便显示一条简单的消息,说明您已到达页面末尾。
【问题讨论】:
有没有办法使用 Jquery 找出页面结束,以便显示一条简单的消息,说明您已到达页面末尾。
【问题讨论】:
How to tell when you're at the bottom of a page:
if ( document.documentElement.clientHeight +
$(document).scrollTop() >= document.body.offsetHeight )
{
// Display alert or whatever you want to do when you're
// at the bottom of the page.
alert("You're at the bottom of the page.");
}
当然,您希望在用户滚动时触发上述内容:
$(window).scroll(function() {
if ( document.documentElement.clientHeight +
$(document).scrollTop() >= document.body.offsetHeight )
{
// Display alert or whatever you want to do when you're
// at the bottom of the page.
alert("You're at the bottom of the page.");
}
});
Here is a jsFiddle example 在用户滚动到页面底部时淡出“你完成了!滚动到页面顶部”链接。
参考资料:
【讨论】:
这会起作用,我在 IE 7,8,9 , FF 3.6, Chrome 6 和 Opera 10.6 中测试过
$(window).scroll(function()
{
if (document.body.scrollHeight - $(this).scrollTop() <= $(this).height())
{
alert('end');
}
});
【讨论】:
如果上述解决方案不起作用,请检查您是否正确设置了文档类型:
<!DOCTYPE HTML>
花了我一个小时才知道:)
【讨论】:
为避免重复console.log('end of page'),您需要创建一个 setTimeout,如下所示:
var doc = $(document), w = $(window), timer;
doc.on('scroll', function(){
if(doc.scrollTop() + w.height() >= doc.height()){
if(typeof timer !== 'undefined') clearTimeout(timer);
timer = setTimeout(function(){
console.log('end of page');
}, 50);
}
});
【讨论】:
可能需要针对浏览器进行调整,但应该这样做:
$(document).scroll(function()
{
var $body = $('body');
if (($body.get(0).scrollHeight - $body.scrollTop) == $body.height())
{
// display your message
}
});
【讨论】:
调试注意事项:我在返回页面顶部时收到警报(?)使用 jquery-1.10.2.js。加载 jquery-1.6.4.min.js,一切正常。
【讨论】:
<script>
$(document).ready(function(){
var a = 1;
//this function triggers whenever scroll is detected
window.addEventListener("scroll", function(){
//this condition is used to trigger alert only once
if(a == 1){
//this condition check whether user scrolled to the
//bottom of the page or not
if(($(document).height()-2) <=
scrollY+$(window).height() ){
alert('end of the page');
a = 0;
}
}
})
});
</script>
【讨论】: