【问题标题】:jQuery load more data on scrolljQuery在滚动上加载更多数据
【发布时间】:2012-12-11 16:37:06
【问题描述】:

我只是想知道只有在 div.loading 可见的情况下,如何才能在滚动上实现更多数据。

通常我们会寻找页面高度和滚动高度,看看是否需要加载更多数据。但是下面的例子就有点复杂了。

下图就是完美的例子。下拉框中有两个 .loading div。当用户滚动内容时,无论哪个可见,它都应该开始为其加载更多数据。

那么我怎样才能知道 .loading div 是否对用户可见?所以我可以开始只为那个 div 加载数据。

【问题讨论】:

    标签: javascript jquery ajax scroll


    【解决方案1】:

    在 jQuery 中,使用滚动功能检查您是否已到达页面底部。一旦你点击它,进行 ajax 调用(你可以在这里显示加载图像直到 ajax 响应)并获取下一组数据,将其附加到 div。当您再次向下滚动页面时,此函数将被执行。

    $(window).scroll(function() {
        if($(window).scrollTop() == $(document).height() - $(window).height()) {
               // ajax call get data from server and append to the div
        }
    });
    

    【讨论】:

    • 这个解决方案很棒而且最简单;) 您可以在 ajax 调用中使用以下行改进此代码:new_element.hide().appendTo('.your_div').fadeIn(); $(window).scrollTop($(window).scrollTop()-1); 第一行以很好的方式附加元素,第二行确保您的函数永远不会在底部停止页面。
    • 我以类似的方式处理此问题,因为您总是在页面底部有任意内容(导航),并且您真的想在触底之前加载。所以我的内在功能是:var end = $("#BottomThing").offset().top; var viewEnd = $(window).scrollTop() + $(window).height(); var distance = end - viewEnd; if (distance < 300) // do load
    • Ryan Bates 对此有一段精彩的插曲:railscasts.com/episodes/114-endless-page。还有一个修订版,但您可能需要订阅。
    • 如果有人想知道用户是否滚动到底部,他可以在此处显示的 if 中使用此 if 条件:if($(window).scrollTop() + $(window)。 height() == $(document).height()) { console.log('滚动到底部!'); }
    • 这个答案不是我在问题中提出的。
    【解决方案2】:

    您听说过jQuery Waypoint plugin

    以下是调用航点插件并在滚动到达底部时让页面加载更多内容的简单方法:

    $(document).ready(function() {
        var $loading = $("<div class='loading'><p>Loading more items&hellip;</p></div>"),
        $footer = $('footer'),
        opts = {
            offset: '100%'
        };
    
        $footer.waypoint(function(event, direction) {
            $footer.waypoint('remove');
            $('body').append($loading);
            $.get($('.more a').attr('href'), function(data) {
                var $data = $(data);
                $('#container').append($data.find('.article'));
                $loading.detach();
                $('.more').replaceWith($data.find('.more'));
                $footer.waypoint(opts);
            });
        }, opts);
    });
    

    【讨论】:

    • 有机会通过 jsfiddle 进行演示吗?
    • 好建议,但最糟糕的 js 插件航路点.. 浪费了我很多时间....下面的答案要快得多,要快得多
    • 您认为以下哪个答案最好?
    • 你可以参考我对延迟加载器实现的回答。 stackoverflow.com/a/45846766/2702249
    【解决方案3】:

    如果不是所有文档都滚动,例如,当您在文档中有滚动的div 时,如果不进行调整,上述解决方案将无法正常工作。下面是如何检查 div 的滚动条是否已经到达底部:

    $('#someScrollingDiv').on('scroll', function() {
        let div = $(this).get(0);
        if(div.scrollTop + div.clientHeight >= div.scrollHeight) {
            // do the lazy loading here
        }
    });
    

    【讨论】:

    • 谢谢兄弟!这真的帮助了我:)
    • 迄今为止最好的答案,谢谢你救命
    【解决方案4】:

    这是一个例子:

    1. 滚动到底部时,会附加 html 元素。这种附加机制只做了两次,最后附加了一个粉蓝色的按钮。

    <!DOCTYPE html>
    <html>
    <head>
        <title>Demo: Lazy Loader</title>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <style>
            #myScroll {
                border: 1px solid #999;
            }
    
            p {
                border: 1px solid #ccc;
                padding: 50px;
                text-align: center;
            }
    
            .loading {
                color: red;
            }
            .dynamic {
                background-color:#ccc;
                color:#000;
            }
        </style>
        <script>
    		var counter=0;
            $(window).scroll(function () {
                if ($(window).scrollTop() == $(document).height() - $(window).height() && counter < 2) {
                    appendData();
                }
            });
            function appendData() {
                var html = '';
                for (i = 0; i < 10; i++) {
                    html += '<p class="dynamic">Dynamic Data :  This is test data.<br />Next line.</p>';
                }
                $('#myScroll').append(html);
    			counter++;
    			
    			if(counter==2)
    			$('#myScroll').append('<button id="uniqueButton" style="margin-left: 50%; background-color: powderblue;">Click</button><br /><br />');
            }
        </script>
    </head>
    <body>
        <div id="myScroll">
            <p>
                Contents will load here!!!.<br />
            </p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
            <p >This is test data.<br />Next line.</p>
        </div>
    </body>
    </html>

    【讨论】:

    • @RohanAshik:我刚刚检查过了。它正在工作。尝试向下滚动到最后。
    • @Om Prakash Sao 在这里工作正常,但是当我在 sublime 中运行此代码时,当滚动条到达顶部而不是底部时,事件就会起作用,\
    【解决方案5】:

    当窗口放大到大于 100% 的值时,此问题的已接受答案与 chrome 存在一些问题。这是 chrome 开发人员推荐的代码,作为我提出的错误的一部分。

    $(window).scroll(function() {
      if($(window).scrollTop() + $(window).height() >= $(document).height()){
         //Your code here
      }
    });
    

    供参考:

    Related SO question

    Chrome Bug

    【讨论】:

    • 我喜欢这个答案,因为它有一个很好的平滑滚动并暂停它。我使用的其他一些方法往往会加载内容过快,这会在尝试真正关注内容而不是加载速度时产生尴尬的体验。
    • 这不适用于移动设备
    【解决方案6】:

    改进@deepakssn 答案。您可能希望数据加载一点我们实际滚动到底部

    var scrollLoad = true;
    $(window).scroll(function(){
     if (scrollLoad && ($(document).height() - $(window).height())-$(window).scrollTop()<=800){
        // fetch data when we are 800px above the document end
        scrollLoad = false;
       }
      });
    

    [var scrollLoad] 用于阻塞调用,直到追加一个新数据。

    希望这会有所帮助。

    【讨论】:

      【解决方案7】:

      我建议使用更多 Math.ceil 以避免某些屏幕上出现错误。
      因为在几个不同的屏幕上它不是绝对准确的
      当我使用 console.log 时,我意识到了这一点。

      console.log($(window).scrollTop()); //5659.20123123890  
      

      console.log$(document).height() - $(window).height()); // 5660
      

      所以我认为我们应该将您的代码编辑为

      $(window).scroll(function() {
          if(Math.ceil($(window).scrollTop()) 
             == Math.ceil(($(document).height() - $(window).height()))) {
                 // ajax call get data from server and append to the div
          }
      });
      

      或者允许在滚动到底部之前从服务器加载数据。

      if ($(window).scrollTop() >= ($(document).height() - $(window).height() - 200)) {
       // Load data
      }
      

      【讨论】:

      • 当用户在不同的浏览器上显示不同的缩放级别时,这个解决方案可以避免不准确。
      【解决方案8】:

      我花了一些时间试图找到一个很好的函数来包装解决方案。无论如何,我认为这是在单个页面或跨站点加载多个内容时更好的解决方案。

      功能:

      function ifViewLoadContent(elem, LoadContent)
          {
                  var top_of_element = $(elem).offset().top;
                  var bottom_of_element = $(elem).offset().top + $(elem).outerHeight();
                  var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
                  var top_of_screen = $(window).scrollTop();
      
                  if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
                  if(!$(elem).hasClass("ImLoaded"))   {
                      $(elem).load(LoadContent).addClass("ImLoaded");
                  }
                  }
                  else {
                     return false;
                  }
              }
      

      然后您可以使用滚动窗口调用该函数(例如,您也可以将其绑定到单击等,就像我也这样做的那样,因此该函数):

      使用方法:

      $(window).scroll(function (event) {
              ifViewLoadContent("#AjaxDivOne", "someFile/somecontent.html"); 
      
              ifViewLoadContent("#AjaxDivTwo", "someFile/somemorecontent.html"); 
          });
      

      这种方法也应该适用于滚动 div 等。我希望它有所帮助,在上面的问题中,您可以使用这种方法分部分加载您的内容,也许附加并因此运球馈送所有图像数据而不是批量馈送。

      我使用这种方法来减少https://www.taxformcalculator.com 的开销。它死了,如果你查看网站并检查元素等,你可以看到对 Chrome 中页面加载的影响(例如)。

      【讨论】:

        【解决方案9】:

        您的问题具体是关于加载数据当 div 进入视图时,而不是当用户到达页面末尾时。

        这是您问题的最佳答案:https://stackoverflow.com/a/33979503/3024226

        【讨论】:

          猜你喜欢
          • 2020-01-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-28
          相关资源
          最近更新 更多