How do i run the .animate function in jQuery forever?

北慕城南 提交于 2019-12-21 04:57:22

问题


$(this).css("left","100px");

function endless(){
    $(this).animate({
        left:'-=100px',
    },{
        easing: "linear",
    duration: 5000,
    complete: function() {
        $(this).css('left','100px');
    endless();
        }
    });
};
endless();

This is what I tried, but using this approach i can't get stuff moving. Im' using jQuery 1.3.2. Any Suggestions?


回答1:


You have the parameters to animate wrong. It doesn't take an options hash, just the actual options for easing, duration, and a callback. Also, you need to take care when using this. Better to pass it in as an argument to the endless function.

$(this).css("left","100px");

function endless(elem){
    $(elem).animate(
        { left:'-=100px' },
        "linear",
        5000,
        function() {
            $(elem).css('left','100px');
            endless(elem);
        }
     );
};
endless(this);



回答2:


You'll need to call endless() from within a callback.

function endless(item) {
  $(item).animate({"left": "-=100px"}, 5000, "linear", function(){
    $(item).css("left","100px");
    endless(item);
  });
}

endless($(".myBox"));



回答3:


You need to replace $(this) with the selector to element that you want to animate.




回答4:


Great! this is exactly what i searched for, but now,

i finally figured how to toggle it. with the following function, call endless(0) to stop, and endless(1) to enable animation loop.

//loop animation forever
//args: takes 1 to loop, 0 to stop
function endless(loop)
{ 
  //animate forever
  if (loop==1)
  {
 $('#alink').animate(
  {'opacity':'toggle'}, 
  1000, 
   function () { endless(1) }
  ); 
  }
  //stop animation
  else
  {
 $('#alink').css('opacity',1).stop();
  }

}; 


//sample call
$('#alink').toggle(function(){ endless(1) },function(){ endless(0) });

thanx for initial code!



来源:https://stackoverflow.com/questions/1206308/how-do-i-run-the-animate-function-in-jquery-forever

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!