2012-08-01 106 views
2

我有这些纸条,我需要循环:jQuery的循环动画

$(document).ready(function() { 
    runIt(); 
}) 
function resets() 
{ 
    $('.grower').removeAttr("style"); 
} 

function runIt() 
    { 
     $('.grower').animate({width: "30px",height: '30px', left: "-6", top: "-6", opacity:"0"}, 800, resets); 
    } 

但是当我加入runIt();它内部自我循环,它循环但我的浏览器变为空白,我不会回应。我怎么能这样做,所以它会循环该动画。

在此先感谢

回答

9

无需查询DOM不断。在一个变量存储$('.grower')

$(document).ready(function() { 
    var $grower = $('.grower'); 

    function runIt() { 
     $grower.animate({ 
      width: "30px", 
      height: '30px', 
      left: "-6", 
      top: "-6", 
      opacity:"0" 
     }, 800, function() { 
      $grower.removeAttr("style"); 
      runIt(); 
     }); 
    } 

    runIt(); 
}); 

这里的小提琴:http://jsfiddle.net/jC8Js/


更新:如果你想让它每个周期前暂停使用​​:

setTimeout(runIt, 1000); 

这里是小提琴:http://jsfiddle.net/jC8Js/1/


或者,你可以只用一个interval timer运行所有的它:

$(document).ready(function() { 
    var $grower = $('.grower'); 

    setInterval(function() { 
     $grower.animate({ 
      width: "30px", 
      height: '30px', 
      left: "-6", 
      top: "-6", 
      opacity:"0" 
     }, 800, function() { 
      $grower.removeAttr("style"); 
     }); 
    }, 1500); 
});​ 

这里的小提琴:http://jsfiddle.net/jC8Js/2/

+0

@YairVillar - 我在每次循环后添加了一些代码以暂停它。 – 2012-08-01 17:33:27

+0

不错的工作,thx! – Lukas 2012-08-30 08:01:15

+0

This: 'function runIt(){... runIt(); }' 可能导致堆栈溢出,因为没有停止条件。直到许多“迭代”才会显示,但在IE9上使用jQuery transition()(而不是animate())时,我遇到了一个类似的问题,它不支持css转换。该次通话是立即进行的,该堆叠快速运行。我认为这种循环方法并不完全是这个循环应该如何完成的。 – kuonirat 2015-07-14 08:26:28

1

http://jsfiddle.net/nUVbb/

$(document).ready(function() { 
    runIt(); 
}) 
function resets() 
{ 
    $('.grower').removeAttr("style"); 
    runIt(); 
} 
function runIt() 
{ 
    $('.grower').animate({width: "30px",height: '30px', left: "-6", top: "-6", opacity:"0"}, 800, resets); 
} 
+0

我怎么给它,它每次循环后的时间? – 2012-08-01 17:24:15

+0

在.animate()之前添加.delay(500) – Tallboy 2012-08-01 19:03:17