javascript animate dosnt循环

时间:2016-12-01 13:02:44

标签: javascript jquery jquery-animate

我有一个轮盘赌游戏,如下所示:enter image description here

我希望它越慢越慢,所以我有这个代码:

$(document).ready(function() {
  $("button").click(function() {
    var moveTime = Math.floor(Math.random() * 1000) + 2000
    var slowDown = 1000;
    while (moveTime > 0) {
      $("div").animate({
        left: slowDown + "px"
      });

      if (slowDown > 0) {
        slowDown--;
        moveTime = 0;
      }
      slowDown--;
      moveTime--;
    }
  });
});
div {
  position: absolute;
  float: left;
  margin: 0 0 0 -8400px;
  width: 10000px;
  height: 100px;
  background: repeating-linear-gradient(90deg, #DF0000, #DF0000 100px, #000000 100px, #000000 200px)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Start Animation</button>
<div></div>

但问题是它只播放动画1次。我也尝试过使用infinityloop,但是也没有用,同样按下按钮两次,第二次没有任何事情发生。

2 个答案:

答案 0 :(得分:3)

您的代码存在的问题是,在连续点击后,div元素已经位于您尝试将其设置为动画的left位置,因此似乎没有任何内容发生。

要解决此问题,请在再次运行动画之前将left位置重置为0。试试这个:

&#13;
&#13;
$(document).ready(function() {
  $("button").click(function() {
    var moveTime = Math.floor(Math.random() * 1000) + 2000
    var slowDown = 1000;
    var $div = $('div').css('left', 0); // < reset the position here

    while (moveTime > 0) {
      $div.animate({
        left: slowDown + "px"
      });

      if (slowDown > 0) {
        slowDown--;
        moveTime = 0;
      }
      
      slowDown--;
      moveTime--;
    }
  });
});
&#13;
div {
  position: absolute;
  float: left;
  margin: 0 0 0 -8400px;
  width: 10000px;
  height: 100px;
  background: repeating-linear-gradient(90deg, #DF0000, #DF0000 100px, #000000 100px, #000000 200px)
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Start Animation</button>
<div></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我不太清楚我是否理解得很好,如果Rory确实给你你想要的答案,但这就是我的建议。

如果您想获得类似轮盘赌的动画,可以使用jQuery的animate以及此处提供的自定义缓动功能:jQuery Easing Plugin

你可以摆脱while循环,只使用animate jQuery函数,以及 Easing Plugin

这是它的样子:

$(document).ready(function() {
  $("button").click(function() {
    
    // Play with these two values
    var nSpin = 4;
    var slow = 2;

    $("div")
      .stop()
      .css({ left: 0 })
      .animate({
        left: nSpin * 1000
      }, slow * nSpin * 1000, 'easeOutExpo');
    
  });
});
div {
  position: absolute;
  float: left;
  margin: 0 0 0 -8400px;
  width: 10000px;
  height: 100px;
  background: repeating-linear-gradient(90deg, #DF0000, #DF0000 100px, #000000 100px, #000000 200px)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js"></script>

<button>Start Animation</button>
<div></div>