2013-07-29 66 views
2

我想在单击同一个div时启动和停止动画。开始和停止使用相同的div(javascript-jquery)

$('div').click(function(){ 

//if is the first click -->do animation in loop 
//if is the second click--->stop animation 

}); 

你是怎么做到的?

我只解决了动画开始循环:

var play = 0; 

function myAnimateGreen(){ 

     $('green').animate(
      {left:'+250px'}, 
      1000, 
      );   
     while(play==1) {myAnimateGreen();} 
    } 

$('green').click(function(){ 
    play = 1; 
    myAnimateGreen();} 
}); 

但我不能消除Stop!

+0

检查'play'是否已经是1,然后将其设置为0. – Barmar

回答

2

可以使用:animated选择检测如果动画正在发生

$('div').click(function(){ 
    if(!$(".green").is(':animated')) { 
     //Do animation 
    } else { 
     //Stop animation 
    } 
}); 
1
function animateGreen(el) { 
    var delay = 500, 
     time = 1000, 
     distance = 150; 
    el.animate({left:'+='+distance+'px'}, time, "linear"); 
    el.data("anim_green", setTimeout(animateGreen, time+delay, el)); 
} 

$('green').click(function() { 
    var self = $(this); 
    if (self.data("anim_green")) { 
     clearTimeout(self.data("anim_green")); 
     self.data("anim_green", false); 
     return; 
    } 
    animateGreen(self); 
}); 

应该这样做,只是贴!证明:http://jsbin.com/ajagij/3/edit

+0

它的工作原理!但是如果在停止后点击againg,它不会重新启动。我该怎么做? – user2631147

+0

对不起,错字。现在,你可以添加延迟(所以你可以点击它!),时间和距离也更容易;) –

+0

优秀的例子(除了使用jsBin而不是jsFiddle)。 +1 – gibberish