2012-07-04 194 views
2

我有一个CSS3动画随机推挤,当我点击“播放”。问题是,当我点击“停止”时,我一直无法停止推动,这是我需要完成的。停止和重新启动CSS3动画

我试图同时使用“-webkit-animation-play-state”和jquery .stop()函数,但无济于事。我觉得我很接近,但看起来似乎不太可能得到这个。

我创建了一个jsfiddle,代码如下。

在此先感谢!

<html> 
<head> 
<style> 
#sec { 
    background: url(http://placekitten.com/200/200); 
    background-repeat:no-repeat; 
    z-index: 3; 
    position: absolute; 
    width: 200px; 
    height: 200px; 
    top: 45px; 
    left: 105px; 
}​ 
</style> 
<script> 
$(document).ready(function(){ 
    $("#play-bt").click(function(){ 
     setInterval(function() { 
     var seconds = Math.random() * -20; 
     var sdegree = seconds * 2 ; 
     var num = -30; 
     var together = num + sdegree; 
     var srotate = "rotate(" + together + "deg)"; 
     $("#sec").css({"-moz-transform" : srotate, "-webkit-transform" : srotate}); 
     }, 100); 
     }); 

    $("#stop-bt").click(function(){ 
      $("#sec").stop(stopAll); 
     }) 

}) 
</script> 
</head> 
<body> 
<div id="sec"></div> 
<br/> 
<div id="play-bt">Play</div> 
<br/> 
<div id="stop-bt">Stop</div> 
</body 
</html> 
+0

这两个解决方案都创建并使用全局变量。我的解决方案的优点是全局变量是布尔类型,而Sam的答案使用函数作为其全局类型。有些事情要考虑,但当然,两者都可以。 – frenchie

+0

@frenchie - 你的答案存在严重问题。你永远不会停止你的代码的时间间隔,你只是阻止它做任何事情。这意味着每次你点击'开始'按钮,你就会产生一个新的动画“线程”。此外,单击开始按钮将激活所有正在运行的线程,如果您反复停止/重新启动,将导致页面严重减速。 –

+0

@frenchie - 同样,在我的回答中,我存储了一个数字,而不是一个函数。 –

回答

2

其用来阻止它是clearInterval()setInterval()的对应物。每次拨打setInterval()时都会返回一个间隔ID,您可以将其传递给clearInterval()以停止它。

因此,您需要存储setInterval()的结果,并在点击stop btn时将其清除。

$(document).ready(function(){ 
    var animation = null; 
    $("#play-bt").click(function(){ 
     if (animation !== null) {  // Add this if statement to prevent 
     return;      // doubled animations 
     } 
     animation = setInterval(function() { 
     var seconds = Math.random() * -20; 
     var sdegree = seconds * 2 ; 
     var num = -30; 
     var together = num + sdegree; 
     var srotate = "rotate(" + together + "deg)"; 
     $("#sec").css({"-moz-transform" : srotate, "-webkit-transform" : srotate}); 
     }, 100); 
     }); 

    $("#stop-bt").click(function(){ 
      //$("#sec").stop(stopAll); 
     if (animation !== null) { 
      clearInterval(animation); 
      animation = null; 
     }   
    }); 

}); 
+0

完美!你是一个拯救生命的人。 – Johan