【发布时间】:2016-09-04 19:28:04
【问题描述】:
我正在制作一个简单的 Simon Says 风格游戏,并使用 for 循环遍历已添加的颜色数组。当前,每次单击按钮时,它都会添加一种颜色并运行 for 循环。我的问题是,当满足两个条件时,不是为一种颜色设置动画,然后是另一种颜色,而是同时为两种颜色设置动画。我尝试使用 setInterval ,它只是做了一个无限循环,而 setTimeout 只是让第一个动画在它发生之前等待。有谁知道我怎样才能让每种颜色一次动画一个?
在我的演示中,请滚动到 js 的底部。顶部是 color.js,它允许彩色动画。单击该按钮几次以查看动画的表现。
var colors = [];
var red, yellow, blue, green;
//random number
mathF = function() {
return Math.random();
};
//determine what color is added
function newColorF() {
var math = mathF();
if(math <= .25) {
newColor = 'red';
}
else if(math <= .5) {
newColor = 'green';
}
else if(math <= .75) {
newColor = 'yellow';
}
else {
newColor = 'blue';
}
return newColor;
}
function computerTurn() {
newColor = newColorF();
colors.push(newColor);
var colorlength = colors.length;
setTimeout(function() {
for(i=0; i<colorlength; i++) {
x = colors[i];
console.log(x);
if(x === 'red') {
$('#red').animate({
backgroundColor: '#ff9e9e'
}, 750)
.delay(250)
.animate({
backgroundColor: 'red'
}, 750);
}
else if(x === 'green') {
$('#green').animate({
backgroundColor: '#bdffbd'
}, 750)
.delay(250)
.animate({
backgroundColor: 'green'
}, 750);
}
else if(x === 'yellow') {
$('#yellow').animate({
backgroundColor: '#ffffc2'
}, 750)
.delay(250)
.animate({
backgroundColor: 'yellow'
}, 750);
}
else {
$('#blue').animate({
backgroundColor: '#a3a3ff'
}, 750)
.delay(250)
.animate({
backgroundColor: 'blue'
}, 750);
}
}
}, 500);
}
//when begin button is pushed
function beginGame() {
computerTurn();
}
$('#startGame').click(function() {
beginGame();
});
【问题讨论】:
标签: javascript jquery loops animation