Jquery .each()包括寻找干净代码的延迟
简而言之,我正在寻找一个jQuery循环,它将选择每个div与一个类(一行中约10个小div)然后执行一些代码在每个div特别淡出和div中包含的图像然后暂停和继续前进并对下一个div做同样的事情。
这个循环同时淡出/包含所有包含的图像……
$('.div_class').each(function() { $(this).children().fadeOut('fast', function() { $(this).fadeIn('slow'); }); });
我查看了jquery函数delay()
和setInterval()
以及本机JavaScript函数setTimeout()
。
我似乎无法让他们完全工作,或者我看到的例子是漫长而复杂的。 有了jquery的魔力,似乎我应该能够在上面的循环中添加非常少的代码,以便它能够串联工作。
如上所述,我正在寻找一个简洁的例子。
您可以将.delay()
与.each()
提供给回调的索引结合使用,如下所示:
$('.div_class').each(function(i) { $(this).children().delay(800*i).fadeOut('fast', function() { $(this).fadeIn('slow'); }); });
这将使它们背对背(快速= 200 +慢= 600),如果你想要更多的延迟,只需将800增加到你想要的任何东西。 在上面的示例中,第一个立即运行,接下来的800毫秒后,接下来的800个,等等。
$('.div_class').each(function(index) { // delay inserted before effect (based off index) $(this).children().delay(index * 1000).fadeOut('fast', function() { $(this).fadeIn('slow'); }); });
* 尼克的眩光 *
这是另一种可行的方式。 这不使用如上所述的定时延迟,而是使用递归方法,其中一个动画的完整将导致下一个的执行。
function animate (elms) { var target = elms[0] if (target) { // guard to ensure still more $(target).children().fadeOut('fast', function() { $(this).fadeIn('slow') // o/` take one down, pass it around, // 98 elements of goop in the list o/` animate(elms.slice(1)) } } } animate($('.div_class').get())