jQuery: fadeIn first n children 一个接一个

jQuery: fadeIn first n children one by one

我是 jQuery 的新手,正在尝试创建一个 Jekyll 主题,它会一一显示前五个 post 元素(段落、标题、图像、要点)。现在,我有一段代码在所有 post 元素中淡出,这 - 不幸的是 - 意味着很长 post 秒,它需要很长时间才能完成。

这是我目前的代码:

$(document).ready(function() {
   $(".post-content").children().each(function(index) {
      $(this).delay(300*index).fadeIn(0);
   });
});

我阅读了一些关于 :lt() 选择器和 slice() 方法的内容,但我还没有找到如何将其中一个与上面的代码结合起来,以便只有前五个 children 动画这边走。我可能只是漏掉了一些愚蠢的东西?

任何指点将不胜感激。谢谢!

您仍然希望 select 整个组,而是检查索引以查看它是否小于 5 并且只对那些应用 .delay(300*index)。您可以立即显示其余内容,也可以根据需要显示其他内容,在此示例中,它将在 1.5 秒延迟后加载其余内容(在第 5 个显示后 ):

$(".post-content").children().each(function(index) {
  if(index < 5)
    $(this).delay(300*index).fadeIn();
  else
    $(this).delay(1500).fadeIn(); //  $(this).fadeIn(); to show immediately 
});
.post-content > * { 
  display: none; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post-content">
  <div>foo1</div>
  <div>foo2</div>
  <div>foo3</div>
  <div>foo4</div>
  <div>foo5</div>
  <div>foo6</div>
  <div>foo7</div>
  <div>foo8</div>
  <div>foo9</div>
  <div>foo10</div>
</div>

这是一个使用切片的工作示例,在 promise 之后只是为了防止您希望在淡入淡出后显示每个元素,如果不只是将其删除

$(document).ready(function() {
   $(".post-content").children().slice(0,5).each(function(index) {
      $(this).delay(300*index).fadeIn(0);
   }).promise().then(function( arg1 ) { 
   $(".post-content").children().slice(5).show()
   });
});

关于 lt 和 slice 的区别,这里有一个解释它们之间区别的答案: Selecting the first "n" items with jQuery

"Though the :lt(20) approach looks much cleaner, using slice is much more efficient if you have a large result set to start with. Unfortunately, when evaluating ":lt" 和其他位置选择器,jQuery 循环遍历整个集合,即使它只是获取第一个元素。我在我的博客上写了更多相关信息: spadgos.com/?p=51