如何循环执行jQuery div动画?

6

我正在尝试使用无限循环的jQuery函数来动画化一个div,但是我不知道该怎么做。以下是我的代码:

$(document).ready(function () {
    $('#divers').animate({
        'margin-top': '90px'
    }, 6000).animate({
        'margin-top': '40px'
    }, 6000);
});

完成了!感谢大家的时间和耐心。 - Eduardo Gustavo Salazar
6个回答

9
将完成整个动画的代码放入一个函数中,然后将该函数作为回调参数传递给最后一个动画。类似于以下内容...
$(document).ready(function() {   
    function animateDivers() {
        $('#divers').animate(
            {'margin-top':'90px'}
            ,6000
        )
        .animate(
            {'margin-top':'40px'}
            ,6000
            ,animateDivers //callback the function, to restart animation cycle
        ); 
    }

    animateDivers(); //call, to start the animation
}); 

嘿,谢谢你提供这个信息。但是请问如果我想移动使用画布放置的图像怎么办? - Narendra Solanki

5
$(document).ready(function() {
    function ani() {
        $('#divers').animate({
               'margin-top':'90px'
            },6000).animate({
               'margin-top':'40px'
           },6000, ani); //call the function again in the callback
        }); 
    }); 
    ani();
}); 

2

使用.animate()回调函数来“调用”你的函数:

jsBin演示

$(function() {
  
  
  function loop(){
   $('#divers')
     .animate({marginTop:90},6000)
     .animate({marginTop:40},6000, loop); // callback
  }
  
  loop(); // call this wherever you want


}); 

它完美地运行了!感谢您花时间制作出如此精彩的演示。非常感激。 - Eduardo Gustavo Salazar

2

使用setInterval是正确的方法。过多的递归会导致"堆栈溢出"错误:)

"未捕获的RangeError:超出最大调用堆栈大小"


1

您还可以设置setInterval函数,指定在什么间隔调用哪个方法。

$(function () { setInterval(fnName, 6000); });

1

animate()函数有一个选项,可以在动画结束时调用一个函数。您可以直接进行相同的调用,完成。


现在我明白了,我只需要看代码就能弄清楚了。非常感谢。 - Eduardo Gustavo Salazar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接