如何在 Javascript/jQuery 中的 DIV 中实现无限/无限滚动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15181286/
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-26 14:33:43  来源:igfitidea点击:

How to implement an endless/infinite scroll within a DIV in Javascript/jQuery

javascriptjqueryhtml

提问by Prabhu

I realize there are several questions here that address the issue of endless scrolling. However most of them are using plugins.

我意识到这里有几个问题可以解决无限滚动的问题。然而,他们中的大多数人都在使用插件。

I'd like to know how to implement endless scrolling that would work with my existing paging functionality. Currently I have a "load more" button, when clicked on, will fetch the next 10 items, and append to the list. Instead of doing this when the "load more" button is clicked, I'd like it to happen when the scroll position comes to the bottom. Also, this list is not on the main page, it's within a DIV. Storing the page number in a hidden field with id 'pageNum'.

我想知道如何实现可与我现有的分页功能一起使用的无限滚动。目前我有一个“加载更多”按钮,当点击时,将获取接下来的 10 个项目,并附加到列表中。与其在单击“加载更多”按钮时执行此操作,不如在滚动位置到达底部时执行此操作。此外,此列表不在主页上,而是在 DIV 中。将页码存储在 ID 为“pageNum”的隐藏字段中。

$.ajax({
        type: "GET",
        url: "/GetItems",
        data: { 'pageNum': $('#pageNum').val() },
        dataType: "json",
        success: function (response) {
                $('#MyDiv ul').append(response.Html);
                $('#pageNum').val(response.PageNum);
            }
        }
});

#MyDiv
{
    border:solid 1px #ccc; 
    width:250px;
    height:500px;
    overflow-y: scroll;
}

<div id="MyDiv">
  <ul>
    <li>...</li>
    ...
  </ul>
</div>

回答by yckart

The simplest way, is to check if you've reached the bottom and to trigger then a click-event on your "load more"-button.

最简单的方法,是检查你是否已经到达底部,并触发然后点击事件上的“加载更多”按钮上。

$(window).on('scroll', function(){
    if( $(window).scrollTop() > $(document).height() - $(window).height() ) {
        $("#load-more").click();
    }
}).scroll();

The script above is just an example, don't use it in your production environment.

上面的脚本只是一个例子,不要在你的生产环境中使用它。

update

更新

...and the better way is to call the function instead of trigger an event which calls the function.

...更好的方法是调用函数而不是触发调用函数的事件。

update2

更新2

...and the best way: let the user decide what is to do if he do (in this case he scrolls down to reach the end of your page, not to reach the next page) ;)

...以及最好的方法:让用户决定如果他这样做要做什么(在这种情况下,他向下滚动以到达页面的末尾,而不是到达下一页);)