使用jQuery进行静态页面的无限滚动

时间:2014-05-09 12:38:32

标签: javascript jquery html symfony infinite-scroll

我编写了一个分页评论部分, 即使你从未使用过symfony2,也很容易理解

它只是循环100条评论,然后使用" next"要显示的下一个评论页面的按钮。

{% for comment in pagination %} 
       <div class="comment-container">
           <div class="bubble">
               <div class="cmt-avatar"></div>
               {{ comment.text }}
           </div>
       </div>
{% endfor %}
到目前为止,这种方法运作良好。 但它使设计看起来很糟糕,特别是在页面右侧有一个巨大的滚动条。 我需要的是一种使其“看起来”的方法。就像在用户滚动时正在加载评论容器一样。它显然只是一个静态页面,它只需要看起来像它的无限滚动。

到目前为止我尝试过的事情:

我在这个页面上找到了这个,它没有工作,没有错误,但什么也没做。

{% for comment in pagination %} 
   <div class="scrollable-data'">
     <div class="comment-container">
           <div class="bubble">
               <div class="cmt-avatar"></div>
               {{ comment.text }}
           </div>
       </div>
   </div>
{% endfor %}

...脚本

var $doc=$(document);
var $win=$(window);

// hide everything that is out of bound
$('.scrollable-data').filter(function(index){
    return ($(this).scrollTop() > $doc.height());
}).hide();

var DATA_INCREMENT=5;

$(window).scroll(function(){
    // test if at the bottom
    if ($doc.height()-$win.height()-$(this).scrollTop() == 0) {
        // show the <DATA_INCREMENT> (5) next hidden data tags
        $('.scrollable-data:hidden:lt('+DATA_INCREMENT+')').show();
    }
});

1 个答案:

答案 0 :(得分:2)

您的例程是脚本错综复杂的。

这就是我实现这个的方法:

一个例程,只显示“当前滚动条中包含的elmenet”(抱歉,没有更好的词语):

function rescroll(){
          //show all
     $('.scrollable-data').show();
        // hide everything that is out of bound
     $('.scrollable-data').filter(function(index){
         console.log($(this).position().top, $(window).height()+$(window).scrollTop());
         return ($(this).position().top > $(window).height()+$(window).scrollTop());
     }).hide();
}

每次用户执行滚动时调用此例程:

$(window).scroll(function(){
  rescroll();
});

然后在页面加载时调用rescroll()

工作示例:http://jsfiddle.net/5WtTU/

一些注意事项:

通常无限滚动有效,当用户滚动到某个评论时,如果他/她向后滚动这些评论,则不会再次隐藏!

所以你应该保存用户滚动的最大值,并始终隐藏直到这一点。这样,如果用户向上滚动,你就不会重新隐藏它。