当滚动到页面底部时使用Jquery提醒

9

是否有一种使用Jquery找出页面末尾的方法,以便显示一个简单的消息,告诉用户已经到达页面底部。


7个回答

18

如何判断网页已经滚动到底部

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 示例,当用户滚动到页面底部时,会淡入一个“您已完成!返回页面顶部”的链接。

参考资料:


1
这对我不起作用。我建议使用SO问题的已接受答案:https://dev59.com/62865IYBdhLWcg3wR8ah - Ryan Burney
@Ryan - jsFiddle对你不起作用吗?你使用的是什么浏览器? - Peter Ajtai

6
这个方法可行,我在IE 7、8、9,Firefox 3.6,Chrome 6和Opera 10.6中进行了测试。
$(window).scroll(function()
{
    if (document.body.scrollHeight - $(this).scrollTop()  <= $(this).height())
    {
        alert('end');
    }
});

2
如果上述解决方案无效,请检查您是否设置了正确的文档类型:
<!DOCTYPE HTML>

花了我一个小时才找到 :)

1
为了避免重复的 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);

    }

});

或者您可以在第一次成功执行(console.log)之后删除事件侦听器。 - Mike Causer

0
 <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>

虽然这段代码可能解决了问题,但如果包括解释如何以及为什么解决问题,将会帮助提高您发布的内容质量,也可能导致更多的赞同。请记住,您回答的是未来读者的问题,而不仅仅是现在提问的人。请编辑您的答案,添加说明,并指出适用的限制和假设。 - Adrian Mole

0

可能需要进行微调以适应不同的浏览器,但是类似这样的代码应该可以胜任:

$(document).scroll(function()
{
    var $body = $('body');
    if (($body.get(0).scrollHeight - $body.scrollTop) == $body.height())
    {
        // display your message
    }
});

0
调试注意事项:我在使用jquery-1.10.2.js时,在返回页面顶部时收到了警报。加载了jquery-1.6.4.min.js后一切正常。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接