2

我想在单击同一个 div 时开始和停止动画。

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

但我无法解决停止!

4

2 回答 2

2

您可以使用:animated选择器来检测动画当前是否正在发生

$('div').click(function(){  
   if( !$(".green").is(':animated') ) {
      //Do animation
   } else {
      //Stop animation
   }
});
于 2013-07-29T17:03:58.357 回答
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

于 2013-07-29T17:07:15.343 回答