我有一个轮盘赌游戏,看起来是这样的:

我希望它越慢越好,所以我有这样的代码:
$(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次动画。我也尝试过无限循环,但这也不起作用,同样的,按下按钮两次,第二次什么都不会发生。
发布于 2016-12-01 13:14:14
代码的问题是,在连续单击时,div元素已经位于您要将其动画到的left位置,因此似乎没有发生任何事情。
若要修复此问题,请在再次运行动画之前将left位置重置为0。试试这个:
$(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--;
}
});
});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>
发布于 2016-12-01 13:47:43
不太确定我是否理解得很好,罗里是否真的给了你你期待的答案,但我的建议如下。
如果您想获得类似轮盘赌的动画,可以使用jQuery的animate,并在这里提供定制的放松功能:jQuery缓解插件。
您可以摆脱while循环,而只使用animate jQuery函数和轻松插件。
如下所示:
$(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>
https://stackoverflow.com/questions/40911371
复制相似问题