简体   繁体   English

jQuery 在滚动时加载更多数据

[英]jQuery load more data on scroll

I am just wondering how can i implement more data on scroll only if the div.loading is visible.我只是想知道如何才能在 div.loading 可见时在滚动上实现更多数据。

Usually we look for page height and scroll height, to see if we need to load more data.通常我们会查找页面高度和滚动高度,看看是否需要加载更多数据。 but the following example is little complicated then that.但下面的例子有点复杂。

Following image is perfect example.下图是完美的例子。 there are two .loading div's on the drop down box.下拉框中有两个 .loading div。 When user scroll the content, whichever is visible it should start loading more data for it.当用户滚动内容时,无论哪个可见,它都应该开始为其加载更多数据。

在此处输入图片说明

So how can i find out if .loading div is visible to user yet or not?那么我如何才能知道 .loading div 是否对用户可见? So i can start loading data for that div only.所以我只能开始加载那个 div 的数据。

In jQuery, check whether you have hit the bottom of page using scroll function.在 jQuery 中,使用滚动功能检查您是否已到达页面底部。 Once you hit that, make an ajax call (you can show a loading image here till ajax response) and get the next set of data, append it to the div.一旦你点击它,进行一个ajax调用(你可以在此处显示加载图像直到ajax响应)并获取下一组数据,将其附加到div。 This function gets executed as you scroll down the page again.当您再次向下滚动页面时,将执行此函数。

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

Have you heard about the jQuery Waypoint plugin .您听说过jQuery Waypoint 插件吗?

Below is the simple way of calling a waypoints plugin and having the page load more Content once you reaches the bottom on scroll :以下是调用航点插件并在滚动到达底部后让页面加载更多内容的简单方法:

$(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);
});

Here is an example:下面是一个例子:

  1. On scrolling to the bottom, html elements are appeneded.滚动到底部时,会附加 html 元素。 This appending mechanism are only done twice, and then a button with powderblue color is appended at last.这种附加机制只做了两次,最后附加了一个粉蓝色的按钮。

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

If not all of your document scrolls, say, when you have a scrolling div within the document, then the above solutions won't work without adaptations.如果不是所有文档都滚动,例如,当文档中有滚动div ,则上述解决方案在没有调整的情况下将无法工作。 Here's how to check whether the div's scrollbar has hit the bottom:下面是如何检查 div 的滚动条是否到达底部:

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

The accepted answer of this question has some issue with chrome when the window is zoomed in to a value >100%.当窗口放大到大于 100% 的值时,此问题的公认答案与 chrome 存在一些问题。 Here is the code recommended by chrome developers as part of a bug i had raised on the same.这是 chrome 开发人员推荐的代码,作为我在同一个问题上提出的错误的一部分。

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

For reference:以供参考:

Related SO question 相关问题

Chrome Bug铬错误

Improving on @deepakssn answer.改进@deepakssn 答案。 There is a possibility that you want the data to load a bit before we actually scroll to the bottom .我们实际滚动到底部之前,您可能希望数据加载一点。

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] is used to block the call until one new data is appended. [var scrollLoad] 用于阻止调用,直到附加一个新数据。

Hope this helps.希望这可以帮助。

I suggest using more Math.ceil for avoid error on some screen.我建议使用更多的 Math.ceil 以避免在某些屏幕上出现错误。
Because on a few different screens it's not absolutely accurate因为在几个不同的屏幕上它不是绝对准确的
I realized that when I console.log.当我使用console.log 时,我意识到了这一点。

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

And

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

So I think we should edit your code to所以我认为我们应该编辑你的代码

$(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
    }
});

Or Allow load data from server before scroll until bottom.或者在滚动到底部之前允许从服务器加载数据。

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

I spent some time trying to find a nice function to wrap a solution.我花了一些时间试图找到一个很好的函数来包装解决方案。 Anyway, ended up with this which I feel is a better solutions when loading multiple content on a single page or across a site.无论如何,最终我认为这是在单个页面上或跨站点加载多个内容时更好的解决方案。

Function:功能:

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;
            }
        }

You can then call the function using window on scroll (for example, you could also bind it to a click etc. as I also do, hence the function):然后,您可以在滚动时使用 window 调用该函数(例如,您也可以像我一样将其绑定到单击等,因此是该函数):

To use:使用:

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

        ifViewLoadContent("#AjaxDivTwo", "someFile/somemorecontent.html"); 
    });

This approach should also work for scrolling divs etc. I hope it helps, in the question above you could use this approach to load your content in sections, maybe append and thereby dribble feed all that image data rather than bulk feed.这种方法也应该适用于滚动 div 等。我希望它有所帮助,在上面的问题中,您可以使用这种方法将内容加载到部分中,可能会附加并由此运载所有图像数据而不是批量提要。

I used this approach to reduce the overhead on https://www.taxformcalculator.com .我使用这种方法来减少https://www.taxformcalculator.com上的开销。 It died the trick, if you look at the site and inspect element etc. you can see impact on page load in Chrome (as an example).如果您查看站点并检查元素等,它就解决了问题。您可以看到对 Chrome 中页面加载的影响(例如)。

You question specifically is about loading data when a div falls into view , and not when the user reaches the end of the page.您的具体问题是在 div 进入 view 时加载数据,而不是在用户到达页面末尾时加载数据。

Here's the best answer to your question: https://stackoverflow.com/a/33979503/3024226这是您问题的最佳答案: https : //stackoverflow.com/a/33979503/3024226

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM