how to loop a jquery div animation?

2019-02-13 17:52发布

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:

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

6条回答
做自己的国王
2楼-- · 2019-02-13 18:14

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
}); 
查看更多
看我几分像从前
3楼-- · 2019-02-13 18:20

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

查看更多
Melony?
4楼-- · 2019-02-13 18:23
$(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();
}); 
查看更多
神经病院院长
5楼-- · 2019-02-13 18:24

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

$(function () { setInterval(fnName, 6000); });
查看更多
虎瘦雄心在
6楼-- · 2019-02-13 18:35

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.

查看更多
萌系小妹纸
7楼-- · 2019-02-13 18:38

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

jsBin demo

$(function() {


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

  loop(); // call this wherever you want


}); 
查看更多
登录 后发表回答