【问题标题】:Infinite scroll for static page with jQuery使用 jQuery 无限滚动静态页面
【发布时间】:2014-05-09 12:38:31
【问题描述】:

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

它只是循环通过 100 个 cmets,然后使用“下一步”按钮显示下一个评论页面。

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

【问题讨论】:

  • 为了清楚起见,在您的脚本中,在滚动功能中,您使用$(window)$win$(this),这三个含义相同。为了更好地阅读,您应该只使用一个。
  • 您可能必须将&lt;div class=".scrollable-data'"&gt; 替换为&lt;div class="scrollable-data"&gt;(没有点也没有顶点)
  • 哎呀,打错字了,原来项目上其实叫 class="scrollable-data"
  • 我从来没有这样做过,但我不确定你的情况if ($doc.height()-$win.height()-$(this).scrollTop() == 0)

标签: javascript jquery html symfony infinite-scroll


【解决方案1】:

您的例程是复杂的脚本。

这就是我的实现方式:

仅显示“在当前滚动条内”包含的 elmenets 的例程(抱歉,没有更好的词):

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/

一些注意事项:

通常无限滚动的工作原理是,当用户滚动到某个评论时,如果他/她向后滚动,这些 cmets 不会再次隐藏!

因此,您应该将用户滚动的最大值保存在某个地方,并一直隐藏到这一点。这样,如果用户向上滚动,您就不会重新隐藏内容。

【讨论】:

  • 如果可行,请考虑将其设置为已接受的答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
相关资源
最近更新 更多