使用我的代码,“灯”一次打开一个,然后一次关闭一个,但我希望一次只打开一个灯。我希望之前打开的灯在下一个灯亮起之前关闭。
http://jsfiddle.net/JoshKerr98/hrpasw0p/
$(document).ready(function() {
var colourInfo = [
{ id: 'square2id', color: ['#FFFF00','#000000'] },
{ id: 'square3id', color: ['#00FF00','#000000'] },
{ id: 'square4id', color: ['#0000FF','#000000'] },
{ id: 'square1id', color: ['#FFFFFF','#000000'] },
{ id: 'square5id', color: ['#FFA500','#000000'] },
];
var changeIndex = 0, colorIndex = 0;
var changeNextBoxColor = function() {
if (!colourInfo[changeIndex]) {
changeIndex = 0;
colorIndex += 1;
}
var info = colourInfo[changeIndex],
color = info.color[colorIndex%info.color.length];
$('#' + info.id).css('background-color', color);
changeIndex += 1;
setTimeout(changeNextBoxColor, 2000);
};
setTimeout(changeNextBoxColor, 2000);
});
答案 0 :(得分:0)
请仔细阅读评论。
$(document).ready(function() {
var colourInfo = [
{ id: 'square2id', color: ['#FFFF00','#000000'] },
{ id: 'square3id', color: ['#00FF00','#000000'] },
{ id: 'square4id', color: ['#0000FF','#000000'] },
{ id: 'square1id', color: ['#FFFFFF','#000000'] },
{ id: 'square5id', color: ['#FFA500','#000000'] }
];
var colorIndex = 0;
// This function sets the color of a box with a certain id
var setColor = function(squareId, color) {
$('#' + squareId).css('background-color', color);
};
// This will make the colorIndex's box black, then increment the index
// and highlight the next box
var changeNextBoxColor = function() {
// Need to make sure to mod (%) by the length of colourInfo
// so that the index doesn't go out of bounds.
var revertSquare = colourInfo[colorIndex % colourInfo.length];
setColor(revertSquare.id, revertSquare.color[1]);
// By using ++colorIndex, you increment colorIndex and the left hand value is
// the incremented value so that changeSquare corresponds to the next element
// in colourInfo
var changeSquare = colourInfo[(++colorIndex) % colourInfo.length];
setColor(changeSquare.id, changeSquare.color[0]);
};
// This repeats the function every 2 seconds (so you don't need to call setTimeout
// inside of changeNextBoxColor).
setInterval(changeNextBoxColor, 2000);
});