滚动到页面末尾时使用Jquery进行警报
有没有办法使用Jquery查找页面结束,以便显示一条简单的消息,说明您已到达页面的末尾。
如何判断您何时位于页面底部 :
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."); } });
这是一个jsFiddle示例 ,当用户滚动到页面底部时,它会淡入“您已完成!滚动到页面顶部”链接。
参考文献:
-
.scroll()
-
.scrollTop()
-
offsetHeight
-
clientHeight
这将工作,我在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'); } });
如果上述解决方案不起作用,请检查您是否正确设置了文档类型:
花了我一个小时才发现:)
为了避免重复的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,一切都很顺利。