2

我有一个 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>
4

1 回答 1

2

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

因此,您需要存储 的结果setInterval(),并在单击停止 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;
        }           
    });

 }); 
于 2012-07-04T01:19:13.683 回答