Javascript 无限滚动jquery插件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5059526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:27:58  来源:igfitidea点击:

infinite-scroll jquery plugin

javascriptjquerycssinfinite-scrolljquery-infinite-scroll

提问by rajh2504

I am trying to set up infinite-scroll on a site I am developing with Coldfusion, I am new to javascript and jquery so I am having some issues wrapping my head around all of this. Do I need to have pagination on my site in order to use the infinite-scroll plugin, or is there a way to do it with out it?

我正在尝试在我使用 Coldfusion 开发的网站上设置无限滚动,我是 javascript 和 jquery 的新手,所以我遇到了一些问题。我是否需要在我的网站上进行分页才能使用无限滚动插件,或者有没有办法不用它?

回答by Hussein

You do not need infinite scroll plug-in for this. To detect when scroll reaches end of page, with jQuery you can do

为此,您不需要无限滚动插件。要检测滚动何时到达页面末尾,您可以使用 jQuery

$(window).scroll(function () { 
   if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
      //Add something at the end of the page
   }
});

Demoon JsFiddle

在 JsFiddle 上演示

回答by Nick

I'm using Hussein's answer with AJAX requests. I modified the code to trigger at 300px instead of 10px, but it started causing my appends to multiply before the AJAX request was finished since the scroll call triggers much more frequently in a 300px range than a 10px range.

我在 AJAX 请求中使用 Hussein 的回答。我修改了代码以在 300 像素而不是 10 像素处触发,但它开始导致我的附加在 AJAX 请求完成之前成倍增加,因为滚动调用在 300 像素范围内比在 10 像素范围内触发的频率要高得多。

To fix this, I added a trigger that would be flipped on successful AJAX load. My code looks more like this:

为了解决这个问题,我添加了一个触发器,它会在成功的 AJAX 加载时翻转。我的代码看起来更像这样:

var scrollLoad = true;

$(window).scroll(function () { 
  if (scrollLoad && $(window).scrollTop() >= $(document).height() - $(window).height() - 300) {
    scrollLoad = false;
    //Add something at the end of the page
  }
});

then in my AJAX response, I set scrollLoadto true.

然后在我的 AJAX 响应中,我设置scrollLoadtrue.

回答by Hawkee

I built on top of Hussein's little example here to make a jQuery widget. It supports localStorage to temporarily save appended results and it has pause functionality to stop the appending every so often, requiring a click to continue.

我在 Hussein 的小例子的基础上构建了一个 jQuery 小部件。它支持 localStorage 来临时保存附加的结果,并且它具有暂停功能以停止附加每隔一段时间,需要单击才能继续。

Give it a try:

试一试:

http://www.hawkee.com/snippet/9445/

http://www.hawkee.com/snippet/9445/

回答by venkatesh

$(function(){ 
    $(window).scroll(function(){
           if($(document).height()<=$(window).scrollTop()+$(window).height()+100){
               alert('end of page');
           }
       });
});

Some one asked for explanation so here is the explanation

有人要求解释,所以这里是解释

here $(document).height()-->is the height of the entire document.In most cases, this is equal to the element of the current document.

这里$(document).height()-->是整个文档的高度。大多数情况下,这等于当前文档的元素。

$(window).height()-->is the height of the window (browser) means height of whatever you are seeing on browser.

$(window).height()--> 是窗口(浏览器)的高度意味着你在浏览器上看到的任何东西的高度。

$(window).scrollTop()-->The Element.scrollTop property gets or sets the number of pixels that the content of an element is scrolled upward. An element's scrollTop is a measurement of the distance of an element's top to its topmost visible content. When an element content does not generate a vertical scrollbar, then its scrollTop value defaults to 0.

$(window).scrollTop()-->Element.scrollTop 属性获取或设置元素内容向上滚动的像素数。元素的 scrollTop 是元素顶部与其最顶部可见内容之间距离的度量。当元素内容不生成垂直滚动条时,则其 scrollTop 值默认为 0。

$(document).height()<=$(window).scrollTop()+$(window).height()+100

add $(window).scrollTop() with $(window).height() now check whether the result is equal to your documnet height or not. if it is equal means you reached at the end.we are adding 100 too because i want to check before the 100 pixels from the bottom of document(note <= in condition)

添加 $(window).scrollTop() 和 $(window).height() 现在检查结果是否等于您的文档网络高度。如果相等,则意味着您到达了最后。我们也添加了 100,因为我想在距文档底部 100 像素之前检查(注意 <= 条件)

please correct me if i am wrong

如果我错了,请纠正我

回答by Vansuita Jr.

If you have a scrollable element, like a div with scroll overflow, but no scrollable document/page, you can take this way.

如果您有一个可滚动元素,例如带有滚动溢出的 div,但没有可滚动的文档/页面,则可以采用这种方式。

       $(function () {
            var s = $(".your-scrollable-element");
            var list = $("#your-table-list");

            /* On element scroll */
            s.scroll(function () {
                /* The scroll top plus element height equals to table height */
                if ((s.scrollTop() + s.height()) == list.height()) {
                    /* you code */
                }
            });
        });

回答by Mojtaba

I had same problem but didn't find suitable plugin for my need. so I wrote following code. this code appends template to element by getting data with ajax and pagination. for detecting when user scrolls to bottom of div I used this condition:

我遇到了同样的问题,但没有找到适合我需要的插件。所以我写了以下代码。此代码通过使用 ajax 和分页获取数据将模板附加到元素。为了检测用户何时滚动到 div 底部,我使用了以下条件:

var t = $("#infiniteContent").offset().top;
var h = $("#infiniteContent").height();
var ws = $(window).scrollTop();
var dh = $(document).height();
var wh = $(window).height();

if (dh - (wh + ws) < dh - (h + t)) {
    //now you are at bottom of #infiniteContent element
}

$(document).ready(function(){
 $.getJSON("https://jsonplaceholder.typicode.com/comments", { _page: 1, _limit:3 }, function (jsonre) {
        appendTemplate(jsonre,1);
    });
});

function appendTemplate(jsonre, pageNumber){
 //instead of this code you can use a templating plugin like "Mustache"
 for(var i =0; i<jsonre.length; i++){
   $("#infiniteContent").append("<div class='item'><h2>"+jsonre[i].name+"</h2><p>"+jsonre[i].body+"</p></div>");
  }

  if (jsonre.length) {
    $("#infiniteContent").attr("data-page", parseInt(pageNumber)+1);
    $(window).on("scroll", initScroll);
    
    //scroll event will not trigger if window size is greater than or equal to document size
    var dh = $(document).height() , wh = $(window).height();
    if(wh>=dh){
     initScroll();
    }
  }
  else {
    $("#infiniteContent").attr("data-page", "");
  }
}

function initScroll() {
    var t = $("#infiniteContent").offset().top;
    var h = $("#infiniteContent").height();
    var ws = $(window).scrollTop();
    var dh = $(document).height();
    var wh = $(window).height();

    if (dh - (wh + ws) < dh - (h + t)) {
        $(window).off('scroll');
        var p = $("#infiniteContent").attr("data-page");
        if (p) {
            $.getJSON("https://jsonplaceholder.typicode.com/comments", { _page: p, _limit:3 }, function (jsonre) {
                appendTemplate(jsonre, p);
            });
        }
    }
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div id="infiniteContent"></div>

回答by John

I wrote this function using Hussein and Nick's ideas, but I wanted it to use promisesfor the callback. I also wanted the infinite scrolling area to be on a fixed div and not just the window if the div is sent into the options object. There is an example of that in my second link below. I suggest using a promise library like Qif you want to support older browsers. The cb method may or may not be a promise and it will work regardless.

我使用 Hussein 和 Nick 的想法编写了这个函数,但我希望它对回调使用promise。如果将 div 发送到选项对象中,我还希望无限滚动区域位于固定 div 上,而不仅仅是窗口。在我下面的第二个链接中有一个例子。如果你想支持旧浏览器,我建议使用像Q这样的承诺库。cb 方法可能是也可能不是承诺,无论如何它都会起作用。

It is used like so:

它是这样使用的:

html

html

<div id="feed"></div>

js

js

var infScroll = infiniteScroll({
    cb: function () {
        return doSomethingPossiblyAnAJAXPromise();     
    }
});

If you want the feed to temporarily stop you can return false in the cb method. Useful if you have hit the end of the feed. It can be be started again by calling the infiniteScroll's returned object method 'setShouldLoad' and passing in true and example to go along with the above code.

如果您希望提要暂时停止,您可以在 cb 方法中返回 false。如果您已到达提要的末尾,则很有用。可以通过调用infiniteScroll 的返回对象方法“setShouldLoad”并传入true 和example 以与上述代码一起重新启动它。

infScroll.setShouldLoad(true);

The function for infinite scrolling is this

无限滚动的功能是这个

function infiniteScroll (options) {
    // these options can be overwritten by the sent in options
    var defaultOptions = {
        binder: $(window), // parent scrollable element
        loadSpot: 300, //
        feedContainer: $("#feed"), // container
        cb: function () { },
    }

    options = $.extend(defaultOptions, options);
    options.shouldLoad = true;

    var returnedOptions = {
        setShouldLoad: function (bool) { options.shouldLoad = bool; if(bool) { scrollHandler(); } },
    };

    function scrollHandler () { 
        var scrollTop = options.binder.scrollTop();
        var height = options.binder[0].innerHeight || options.binder.height();
        if (options.shouldLoad && scrollTop >= (options.binder[0].scrollHeight || $(document).height()) - height - options.loadSpot) {
            options.shouldLoad = false;
            if(typeof options.cb === "function") {
                new Promise(function (resolve) {resolve();}).then(function() { return options.cb(); }).then(function (isNotFinished) {
                    if(typeof isNotFinished === "boolean") {
                        options.shouldLoad = isNotFinished;
                    }
                });
            }
        }
    }

    options.binder.scroll(scrollHandler);

    scrollHandler();

    return returnedOptions;

}

1 feed example with window as scroller

1 个以窗口为滚动条的提要示例

2 feed example with feed as scroller

2 Feed 示例,以 Feed 作为滚动条