如何循环 jQuery div 动画?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13367036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:34:25  来源:igfitidea点击:

How to loop a jQuery div animation?

jqueryloopsjquery-animate

提问by Eduardo Gustavo Salazar

I'm trying to implement a jQuery function with an infinite loop to animate a div. I can't figure out how to do it. This is my code:

我正在尝试使用无限循环来实现一个 jQuery 函数来为 div 设置动画。我不知道该怎么做。这是我的代码:

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

回答by madlee

put the code that does the full animation into a function, then pass that function as the callback param to the last animation. Something like...

将执行完整动画的代码放入一个函数中,然后将该函数作为回调参数传递给最后一个动画。就像是...

$(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
}); 

回答by adeneo

$(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();
}); 

回答by Roko C. Buljan

use the .animate()callback to 'recall' your function:

使用.animate()回调来“召回”你的功能:

jsBin demo

jsBin 演示

$(function() {


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

  loop(); // call this wherever you want


}); 

回答by eyal_katz

Using setInterval is the way to go. Too much recursion will just get you "Stack Overflow" :-) "Uncaught RangeError: Maximum call stack size exceeded"

使用 setInterval 是可行的方法。太多的递归只会让你“堆栈溢出”:-)“未捕获的范围错误:超出最大调用堆栈大小”

回答by thatidiotguy

The animate()function has an option to take a function to call when the animation ends. You could just do the same call, and voila.

animate()函数可以选择在动画结束时调用一个函数。你可以做同样的电话,瞧。

回答by JJschk

You can also set the set interval function specifying which method to call at what interval

您还可以设置 set interval 函数指定在什么时间间隔调用哪个方法

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