javascript - jQuery 立即停止动画

标签 javascript jquery css

我每隔一秒就有一个动画,我有一个停止按钮,当我点击该按钮时,动画停止但之后继续。没有其他方法可以删除动画吗? 这是我的 code .

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

谢谢

最佳答案

jsFiddle demo

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

});

关于javascript - jQuery 立即停止动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13017882/

相关文章:

java - GWT:如何使用服务器端排列选择?

javascript - JQuery - 在一个函数中访问一个 VAR,而我将在另一个函数中需要它?

javascript - 从 IP 获取地理位置,使用 "ipinfodb"

jquery - dojo.create() 的 jQuery 等价物是什么?

javascript - Contenteditable 在子节点上设置插入符号

jQuery slider 无法加载第一张图片

javascript - 通过单击与其关联的 <a> 来检查单选按钮

javascript - addClass() 基于另一个类的存在?

javascript - IronRouter waitOn、数据和 onAfterAction 困惑

html - 如何使 Bootstrap 中的特定元素不使用主题样式?