【问题标题】:Detecting when user scrolls to bottom of div with jQuery检测用户何时使用 jQuery 滚动到 div 的底部
【发布时间】:2011-09-10 09:41:57
【问题描述】:

我有一个 div 框(称为 Flux),里面有不同数量的内容。 此 divbox 已将溢出设置为自动。

现在,我想做的是,当使用滚动到此 DIV 框的底部时,将更多内容加载到页面中,我知道如何执行此操作(加载内容)但我不知道知道如何检测用户何时滚动到 div 标签的底部? 如果我想对整个页面执行此操作,我会使用 .scrollTop 并从 .height 中减去它。

但我在这里似乎不能这样做?

我尝试从flux中获取.scrollTop,然后将所有内容包装在一个名为inner的div中,但如果我使用flux的innerHeight,它返回564px(div设置为500作为高度)和高度'innner' 它返回 1064,当在 div 底部时,滚动顶部显示 564。

我能做什么?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您可以使用一些属性/方法:

    $().scrollTop()//how much has been scrolled
    $().innerHeight()// inner height of the element
    DOMElement.scrollHeight//height of the content of the element
    

    所以你可以取前两个属性之和,当它等于最后一个属性时,你已经到了结尾:

    jQuery(function($) {
        $('#flux').on('scroll', function() {
            if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
                alert('end reached');
            }
        })
    });
    

    http://jsfiddle.net/doktormolle/w7X9N/

    编辑:我已将“绑定”更新为“开启”:

    从 jQuery 1.7 开始,.on() 方法是将事件处理程序附加到文档的首选方法。

    【讨论】:

    • 它会在 DOM 准备好确保 #flux-element 已经可用时进行绑定。
    • 您应该使用 ON 而不是 bind 来更新您的答案,不推荐使用 bind 来支持 On
    • 注意:当用户在浏览器上使用缩放级别时,这可能不起作用。 Zoom 导致innerHeight() 报告小数。在用户缩小的情况下,scrollTop()innerHeight() 的总和将始终至少比scrollHeight 少一小部分。我最终添加了一个 20 像素的缓冲区。结果条件为if(el.scrollTop() + el.innerHeight() >= el[0].scrollHeight - 20),其中el 等于$(this)
    • 这是有史以来最适合我的最佳答案。谢谢
    • 它不再工作了,请你确认它为什么不能工作,谢谢
    【解决方案2】:

    我找到了一个解决方案,当您滚动窗口并从底部显示 div 的末尾时会发出警报。

    $(window).bind('scroll', function() {
        if($(window).scrollTop() >= $('.posts').offset().top + $('.posts').outerHeight() - window.innerHeight) {
            alert('end reached');
        }
    });
    

    在这个例子中,如果你在 div (.posts) 完成时向下滚动,它会给你一个警报。

    【讨论】:

    • 谢谢你,但是当它到达那个 div 的底部时,我怎样才能让 div 动画呢?同样,当您向上滚动时,检测到该 div 的顶部,然后也进行动画处理。就像这个网站上的lazada.com.ph/apple边栏行为希望你能帮助我:)
    • 它就像魔术一样工作,但问题是警报被执行了两次,所以如果你在里面调用了一个函数,它将被执行两次
    • @1616 我在此之前声明了一个变量var running = false。在条件内,我检查if(!running) { running = true; // and continue logic } 这样它只被调用一次! AJAX 完成后,设置running = false;
    • 是关于window的,问题是关于div的。
    【解决方案3】:

    尽管这个问题是在 5.5 年前提出的,但它在今天的 UI/UX 环境中仍然具有重要意义。我想加两分钱。

    var element = document.getElementById('flux');
    if (element.scrollHeight - element.scrollTop === element.clientHeight)
        {
            // element is at the end of its scroll, load more content
        }
    

    来源:https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Determine_if_an_element_has_been_totally_scrolled

    某些元素不允许您滚动元素的整个高度。在这些情况下,您可以使用:

    var element = docuement.getElementById('flux');
    if (element.offsetHeight + element.scrollTop === element.scrollHeight) {
      // element is at the end of its scroll, load more content
    }
    

    【讨论】:

    • 如果您不使用 jQuery,这就是您正在寻找的解决方案。
    • 有事件处理器吗?
    • @AlexanderVolkov onscroll 是相关事件。
    【解决方案4】:

    这里只是一个附加说明,因为我在寻找我想要滚动的固定 div 的解决方案时发现了这一点。对于我的场景,我发现最好考虑 div 上的填充,这样我就可以准确地结束。因此,扩展@Dr.Molle 的答案,我添加了以下内容

    $('#flux').bind('scroll', function() {
        var scrollPosition = $(this).scrollTop() + $(this).outerHeight();
        var divTotalHeight = $(this)[0].scrollHeight 
                              + parseInt($(this).css('padding-top'), 10) 
                              + parseInt($(this).css('padding-bottom'), 10)
                              + parseInt($(this).css('border-top-width'), 10)
                              + parseInt($(this).css('border-bottom-width'), 10);
    
        if( scrollPosition == divTotalHeight )
        {
          alert('end reached');
        }
      });
    

    这将为您提供准确的位置,包括内边距和边框

    【讨论】:

      【解决方案5】:

      这对我有用

      $(window).scroll(function() {
        if ($(window).scrollTop() >= (($(document).height() - $(window).height()) - $('#divID').innerHeight())) {
          console.log('div reached');
        }
      });
      

      【讨论】:

        【解决方案6】:

        在简单的 DOM 使用中,您可以检查条件

        element.scrollTop + element.clientHeight == element.scrollHeight
        

        如果为真,那么你已经走到了尽头。

        【讨论】:

          【解决方案7】:

          如果您需要在具有 overflow-y 作为隐藏或滚动的 div 上使用它,那么您可能需要这样的东西。

          if ($('#element').prop('scrollHeight') - $('#element').scrollTop() <= Math.ceil($('#element').height())) {
              at_bottom = true;
          }
          

          我发现需要 ceil 是因为 prop scrollHeight 似乎是圆形的,或者可能是其他一些原因导致它小于 1。

          【讨论】:

            【解决方案8】:

            如果您不使用 Math.round() 函数,Dr.Molle 的解决方案 suggested 在浏览器窗口具有缩放功能的某些情况下将不起作用。

            例如 $(this).scrollTop() + $(this).innerHeight() = 600

            $(this)[0].scrollHeight 产量 = 599.99998

            600 >= 599.99998 失败。

            这是正确的代码:

            jQuery(function($) {
                $('#flux').on('scroll', function() {
                    if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10)) {
                        alert('end reached');
                    }
                })
            });
            

            如果您不需要严格的条件,您还可以添加一些额外的边距像素

            var margin = 4
            
            jQuery(function($) {
                $('#flux').on('scroll', function() {
                    if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10) - margin) {
                        alert('end reached');
                    }
                })
            });
            

            【讨论】:

              【解决方案9】:

              虽然这个问题已经问了将近 6 年,但在 UX 设计中仍然是热门话题,如果有新手想使用,这里有 demo sn-p

              $(function() {
              
                /* this is only for demonstration purpose */
                var t = $('.posts').html(),
                  c = 1,
                  scroll_enabled = true;
              
                function load_ajax() {
              
                  /* call ajax here... on success enable scroll  */
                  $('.posts').append('<h4>' + (++c) + ' </h4>' + t);
              
                  /*again enable loading on scroll... */
                  scroll_enabled = true;
              
                }
              
              
                $(window).bind('scroll', function() {
                  if (scroll_enabled) {
              
                    /* if 90% scrolled */
                  if($(window).scrollTop() >= ($('.posts').offset().top + $('.posts').outerHeight()-window.innerHeight)*0.9) {
              
                      /* load ajax content */
                      scroll_enabled = false;  
                      load_ajax();
                    }
              
                  }
              
                });
              
              });
              h4 {
                color: red;
                font-size: 36px;
                background-color: yellow;
              }
              <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
              <div class="posts">
                Lorem ipsum dolor sit amet  Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut libero Curabitur id <br> Dui pretium hendrerit
                sapien Pellentesque <br> Lorem ipsum dolor sit amet <br> Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut libero Curabitur id <br>  Dui pretium hendrerit sapien Pellentesque <br> Lorem ipsum dolor sit amet <br> Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut
                libero Curabitur id <br> Dui pretium hendrerit sapien Pellentesque <br> Lorem ipsum dolor sit amet <br> Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet
                lacus Donec <br> Ut ut libero Curabitur id <br> Dui pretium hendrerit sapien Pellentesque
              </div>

              【讨论】:

                【解决方案10】:

                如果有人将scrollHeight 设为undefined,则选择元素的第一个子元素:mob_top_menu[0].scrollHeight

                【讨论】:

                  【解决方案11】:

                  不确定是否有帮助,但我就是这样做的。

                  我有一个比窗口大的索引面板,我让它滚动直到到达这个索引的末尾。然后我将其固定到位。一旦您滚动到页面顶部,该过程就会反转。

                  问候。

                  <style type="text/css">
                      .fixed_Bot {    
                              position: fixed;     
                              bottom: 24px;    
                          }     
                  </style>
                  
                  <script type="text/javascript">
                      $(document).ready(function () {
                          var sidebarheight = $('#index').height();
                          var windowheight = $(window).height();
                  
                  
                          $(window).scroll(function () {
                              var scrollTop = $(window).scrollTop();
                  
                              if (scrollTop >= sidebarheight - windowheight){
                                  $('#index').addClass('fixed_Bot');
                              }
                              else {
                                  $('#index').removeClass('fixed_Bot');
                              }                   
                          });
                      });
                  
                  </script>
                  

                  【讨论】:

                    【解决方案12】:

                    这是另一个版本。

                    关键代码是函数scroller(),它使用overflow:scroll将输入作为包含滚动部分的div的高度。它大约距顶部 5 像素或距底部 10 像素,如顶部或底部。否则太敏感了。似乎 10px 大约是最小值。您会看到它在 div 高度上增加了 10 以获得底部高度。我认为 5px 可能会起作用,我没有进行广泛的测试。 YMMV。 scrollHeight 返回内部滚动区域的高度,而不是 div 的显示高度,本例中为 400px。

                    <?php
                    
                    $scrolling_area_height=400;
                    echo '
                    <script type="text/javascript">
                              function scroller(ourheight) {
                                var ourtop=document.getElementById(\'scrolling_area\').scrollTop;
                                if (ourtop > (ourheight-\''.($scrolling_area_height+10).'\')) {
                                    alert(\'at the bottom; ourtop:\'+ourtop+\' ourheight:\'+ourheight);
                                }
                                if (ourtop <= (5)) {
                                    alert(\'Reached the top\');
                                }
                              }
                    </script>
                    
                    <style type="text/css">
                    .scroller { 
                                display:block;
                                float:left;
                                top:10px;
                                left:10px;
                                height:'.$scrolling_area_height.';
                                border:1px solid red;
                                width:200px;
                                overflow:scroll; 
                            }
                    </style>
                    
                    $content="your content here";
                    
                    <div id="scrolling_area" class="scroller">
                    onscroll="var ourheight=document.getElementById(\'scrolling_area\').scrollHeight;
                            scroller(ourheight);"
                            >'.$content.'
                    </div>';
                    
                    ?>
                    

                    【讨论】:

                    • -1 因为从 php 生成 javascript+css 代码是不好的做法(难以维护、没有可重用性、没有网站优化等)。此外,正如@Alexander Millar 所指出的,可以通过考虑填充来修复 10px 偏移量。任何考虑使用此代码的人都应该三思……
                    【解决方案13】:

                    伙计们,这是缩放问题的解决方案,它适用于所有缩放级别,以防你需要它:

                    if ( Math.abs(elem.offset().top) + elem.height() + elem.offset().top >= elem.outerHeight() ) {
                                        console.log("bottom");
                                        // We're at the bottom!
                                    }
                                });
                            }
                    

                    【讨论】:

                      【解决方案14】:
                      $(window).on("scroll", function() {
                          //get height of the (browser) window aka viewport
                          var scrollHeight = $(document).height();
                          // get height of the document 
                          var scrollPosition = $(window).height() + $(window).scrollTop();
                          if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
                              // code to run when scroll to bottom of the page
                          }
                      });
                      

                      This是github上的代码。

                      【讨论】:

                        【解决方案15】:

                        我已经编写了这段代码,用于检测我何时滚动到元素的末尾!

                        let element = $('.element');
                        
                        if ($(document).scrollTop() > element.offset().top + element.height()) {
                        
                             /// do something ///
                        }
                        

                        【讨论】:

                          【解决方案16】:

                          没有一个对我有用,这个对我有用:

                          $(window).on('scroll', function() {
                              if ($(window).scrollTop() >= $('#flux').offset().top + $('#flux').outerHeight() - window.innerHeight) {
                                  alert('You reached the end of the DIV');
                              }
                          });
                          

                          【讨论】:

                            猜你喜欢
                            • 1970-01-01
                            • 2018-01-17
                            • 1970-01-01
                            • 1970-01-01
                            • 2012-04-16
                            • 2012-03-30
                            • 2012-10-04
                            相关资源
                            最近更新 更多