循环使用.each延迟Jquery

我不擅长jQuery所以我不确定我的假设是否正确。

我正在使用同位素插件,我希望逐个插入元素(而不是一次性插入)稍微延迟,所以它看起来也像它(对于人眼)

插入我使用的同位素项目

$('#container').isotope( 'insert', $item); 

所以为了逐个插入我正在做的事情

 $("#items_are_here").find('.item').each(function( index ) { setTimeout(function() { $('#container').isotope( 'insert', $(this)); },3000); }); 

然而,这似乎是浏览器等待某些东西,然后立即显示它们

如果我做

  setTimeout(function() { $("#items_are_here").find('.item').each(function( index ) { $('#container').isotope( 'insert', $(this)); }); },3000); 

一切正常,但不是一个一个..

这是正确的方法吗? 还是我过于复杂了?

这里是小提琴 。 在其中,有2个buttosn – 全部插入 – 它找到所有.item并插入它们。 并逐个插入,以延迟方式执行建议的方式。 如你所见,没有延迟。

  var $items=$("#items_are_here").find('.item'); var i=-1; var delayed=setinterval(function() { if (++i<$items.length) $('#container').isotope( 'insert', $items.eq(i)); else clearInterval(delayed); },3000); 

未经测试。 要么

  var $container=$('#container'); $.fn.extend({ onebyone :function ($ctnr,i) { if (!i) i = 0; var $o=$(this); setTimeOut(function() { $ctnr.isotope( 'insert', $o.eq(i)); if (++i<$o.length) $o.onebyone(i); },3000); return this; } $("#items_are_here").find('.item').onebyone($container); 

因为.each()对于每个条目都是瞬时运行的,所以你最终会得到一堆或多或少相同的超时。 因此,大约3秒后,所有超时都会过期,并添加项目。

为了防止这种情况,您将使超时取决于项目的索引。 因此,项目0将在3秒后插入,项目1将在6秒后插入,等等。

 $("#items_are_here").find('.item').each(function( index ) { var item = $(this); setTimeout(function() { $('#container').isotope('insert', item); },3000 * (index + 1)); }); 
 $("#items_are_here").find('.item').each(function( index ) { setTimeout(function() { $('#container').isotope( 'insert', $(this)); },3000); }); 

在上面的上下文中, $(this)window对象,因为它在setTimeout

修改您的代码并尝试:

 $("#items_are_here").find('.item').each(function( index ) { var item = $(this); setTimeout(function(index) { $("#container").isotope( 'insert', $(this)) },index*3000); }); 
 $("#items_are_here").find('.item').each(function( index ) { var item = $(this); setTimeout(function(i) { $('#container').isotope( 'insert', i ); },3000); }); 

我的解决方法是:将类强制编码为类似to_animate的项目

css:

.item.to_animate { opacity:0; display:block; } @keyframes TransitionClass{ 0% { opacity: 0;transform: scale(1.2); } 100% { opacity: 1;transform: scale(1); } } .animatefinish.TransitionClass{ animation-name: umScaleIn; animation-timing-function: cubic-bezier(0.19,1,.22,1); } .animatefinish.TransitionClass{ animation-duration: .8s; }

为同位素剪了一下

  `$('#container').isotope( 'appended', $(el) ).after(function() { $('.item.to_animate').each(function(i) { var el = $(this); setTimeout(function() { el.addClass('TransitionClass animatefinish'); el.removeClass('to_animate') }, i * 200); }); });`