如何在jQuery中重复函数调用
我有这个代码:
$(document).ready(function() { function loop(){ $('#picOne').fadeIn(0).fadeOut(8000); $('#picTwo').delay(2000).fadeIn(6000).fadeOut(5000); $('#picTree').delay(10000).fadeIn(2000).fadeOut(16000); $('#picFour').delay(12000).fadeIn(16000).fadeOut(5000); } loop(); });
但是当最后一张图片淡出时,代码不会重复。 问题是什么?
假设您希望每个元素的动画持续时间相同:
var $elements = $('#picOne, #picTwo, #picTree, #picFour'); function anim_loop(index) { // Get the element with that index and do the animation $elements.eq(index).fadeIn(1000).delay(3000).fadeOut(1000, function() { // Kind of recursive call, increasing the index and keeping in the // the range of valid indexes anim_loop((index + 1) % $elements.length); }); } anim_loop(0); // start with the first element
我不确切知道动画应该是怎样的,但我希望它能让这个概念变得清晰。
更新:要在一段时间后同时淡出并在图像中,请使用setTimeout
并在回调中调用fadeOut
和anim_loop
:
$elements.eq(index).fadeIn(1000, function() { var $self = $(this); setTimeout(function() { $self.fadeOut(1000); anim_loop((index + 1) % $elements.length); }, 3000); });
DEMO
没有问题,你的function只被调用一次。
如果你想循环它们你可以使用setInterval()
或setTimeout()
setInterval(function(){loop()}, 16000); function loop(){ $('#picOne').fadeIn(0).fadeOut(8000); $('#picTwo').delay(2000).fadeIn(6000).fadeOut(5000); $('#picTree').delay(10000).fadeIn(2000).fadeOut(16000); $('#picFour').delay(12000).fadeIn(16000).fadeOut(5000); }
要么
function loop(){ $('#picOne').fadeIn(0).fadeOut(8000); $('#picTwo').delay(2000).fadeIn(6000).fadeOut(5000); $('#picTree').delay(10000).fadeIn(2000).fadeOut(16000); $('#picFour').delay(12000).fadeIn(16000).fadeOut(5000); setTimeout(function(){loop()}, 16000); }
在这两种情况下,函数将每16 seconds = 16000 miliseconds
调用16 seconds = 16000 miliseconds
。
我想说这个function确实运行良好,无论谁做了,都做得很好。 我编辑了演示,它适用于图片。
function
var $elements = $('#picOne, #picTwo, #picTree, #picFour'); function anim_loop(index) { $elements.eq(index).fadeIn(1000, function() { var $self = $(this); setTimeout(function() { $self.fadeOut(1000); anim_loop((index + 1) % $elements.length); }, 3000); }); } anim_loop(0); // start with the first element