我对jQuery相当陌生,我试图创建一个Jekyll主题,它一个一个地显示前五个post元素(段落、标题、图像、要点)。现在,我有一段代码在所有post元素中消失,不幸的是,这意味着对于非常长的帖子,它需要很长时间才能完成。
下面是我到目前为止掌握的代码:
$(document).ready(function() {
$(".post-content").children().each(function(index) {
$(this).delay(300*index).fadeIn(0);
});
});
我读过一些关于:lt()
选择器和slice()
方法的文章,但是我还没有找到如何将其中的一种方法与上面的代码结合起来,所以只有前五个孩子才会这样做。我可能只是错过了一些愚蠢的东西?
任何指示都将不胜感激。谢谢!
发布于 2018-03-06 16:08:26
您仍然希望选择整个组,而不是检查索引,看看它是否小于5,并且只对这些组应用.delay(300*index)
。您可以立即显示rest,也可以以任何其他方式显示,在本例中,它将在延迟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>
发布于 2018-03-06 16:31:03
下面是一个关于切片的工作示例,在承诺之后,如果您希望在淡出之后显示每个元素,如果不只是删除它的话
$(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()
});
});
关于它和切片的差异,下面是一个解释它们之间的区别的答案:Selecting the first "n" items with jQuery
“虽然:lt(20)方法看起来要干净得多,但是如果一开始就有一个很大的结果集,那么使用片的效率要高得多。不幸的是,当评估":lt”和其他位置选择器时,jQuery循环整个集合,即使它只是得到第一个元素。我在这里写了更多关于这个问题的文章: spadgos.com/?p=51“
https://stackoverflow.com/questions/49141939
复制