立即停止动画jQuery

3
我每一秒钟都有一个动画,我还有一个停止按钮,当我点击按钮时,动画会停止,但之后它又会继续。难道没有其他方法可以移除动画吗? 这是我的代码
 $(document).ready(function() {
    setInterval(function() {
        $("#myImg").animate({top: '50%',left: '50%',width: '174px',height: '174px',padding: '10px'}, 500);
         $("#myImg").animate({ marginTop: '0',marginLeft: '0',top: '0',left: '0',width: '70px',height: '70px',padding: '5px'}, 600); 
   },1000);    
});


$("#stop").click(function(){
$("#myImg").stop();
});

谢谢。

你有在1000的区间内500+600,难道不是这样吗? - Santiago Rebella
1
是的,但这不是问题:http://jsfiddle.net/Mils/UxTdU/11/ - Mils
2个回答

3

jsFiddle演示

  1. -你不需要使用setInterval,可以使用.animate()回调函数来循环执行你的anim函数。
  2. -嵌套你的动画函数。
  3. -在第一次.animate()迭代中使用.stop()方法,以避免动画堆积并清除一些动画内存;)
$(document).ready(function() {
    
   function anim(){
       $("#myImg").stop().animate({top: '50%',left: '50%',width: '174px',height: '174px',padding: '10px'}, 500, function(){
            $(this).animate({ marginTop: '0',marginLeft: '0',top: '0',left: '0',width: '70px',height: '70px',padding: '5px'}, 600, anim); // <-- the 'anim' callback
       });    // SCROLL THERE --> TO FIND THE CALLBACK :D --> 
    }
    anim(); // run!!



    $("#stop").click(function(){
        $("#myImg").stop();
    });

});

1

setInterval() 调用会不断地向您的元素添加新的 .animate() 调用。这意味着如果您成功停止了动画,那么 setInterval() 会再次调用它,使动画重新运行。

为什么要在 setInterval() 上使用这个?

无论如何,您也必须取消计划。您可以通过执行类似以下内容的操作来实现:

var schedule = setInterval(fn, 1000);
clearInterval(schedule);

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