如何基于用户滚动加载网页内容

gou*_*rav 25 javascript jquery

如何在用户滚动网页时加载内容.怎么实现这个?

Dut*_*432 38

一般来说,你需要有这样的结构

....first page of content...
....first page of content...
....first page of content...
....first page of content...
....first page of content...
....first page of content...
....first page of content...
<div id="placeHolder"></div>
Run Code Online (Sandbox Code Playgroud)

然后,您需要检测何时接近页面末尾,并获取更多数据

 $(window).scroll(function(){
      if  ($(window).scrollTop() == $(document).height() - $(window).height()){
           AddMoreContent();
      }
 });    

 function AddMoreContent(){
      $.post('getMoreContent.php', function(data) {
           //Assuming the returned data is pure HTML
           $(data).insertBefore($('#placeHolder'));
      });
 }
Run Code Online (Sandbox Code Playgroud)

您可能需要保留一个名为诸如lastId存储最后显示的id之类的javascript变量,并将其传递给AJAX接收器,以便它知道要返回哪些新内容.然后在你的AJAX中你可以打电话

      $.post('getMoreContent.php', 'lastId=' + lastId, function(data) {
           //Assuming the returned data is pure HTML
           $(data).insertBefore($('#placeHolder'));
      });
Run Code Online (Sandbox Code Playgroud)

我在公司的搜索页面上做到了这一点.


pat*_*rox 13

只是为了扩展Dutchie432.根据我的经验

if ($(window).scrollTop() == $(document).height() - $(window).height())

可能不是一贯的真实(个人我不能使它成为真正的因为它跳跃数字).
此外,如果用户向上和向下滚动它可能会触发许多请求,而我们正在等待第一个ajax调用返回.

所以我做的就是使用> =而不是==.然后,在发出我的ajax请求之前取消绑定scrollTop.如果ajax已经返回任何数据(这意味着可能有更多),则再次绑定它.

这里是

<script type="text/javascript">
  $(document).ready(function(){                
        $(window).bind('scroll',fetchMore);
   });

   fetchMore = function (){
       if ( $(window).scrollTop() >= $(document).height()-$(window).height()-300 ){
           $(window).unbind('scroll',fetchMore);
            $.post('ajax/ajax_manager.php',{'action':'moreReviews','start':$('.review').length,'step':5 },
            function(data) {
               if(data.length>10){
                    $(data).insertBefore($('#moreHolder'));
                    $(window).bind('scroll',fetchMore);
               }
            });
        }
   }
</script>
Run Code Online (Sandbox Code Playgroud)

`

  • 我发现这个答案中的想法肯定改善了Dutchie432的绝佳答案. (2认同)

小智 6

您可以使用 window.addeventlistener 跟踪网页的滚动行为,并在用户位于网页底部时向页面加载更多内容。

document.documentElement.scrollTop、document.documentElement.clientHeight 和 document.documentElement.scrollHeight 将帮助您实现此目标。

例如:

window.addEventListener('scroll',()=>{
  const {scrollTop,clientHeight,scrollHeight} = document.documentElement;
  if ((scrollTop+clientHeight)>=scrollHeight) {
    getContent((current_page+1));
  }
});
Run Code Online (Sandbox Code Playgroud)


Fei*_*ngo 5

您指的是动态渐进加载。

这是一个文档详尽的概念,甚至其他库也对此提供了一些内置支持。JQuery实际上有一个GridView,例如,它很容易支持渐进式加载。

您将需要利用AJAX来实现此功能。