我该怎么做才能让一盏灯熄灭然后另一盏灯熄灭

时间:2016-03-24 15:27:49

标签: javascript html css

使用我的代码,“灯”一次打开一个,然后一次关闭一个,但我希望一次只打开一个灯。我希望之前打开的灯在下一个灯亮起之前关闭。

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);
});

1 个答案:

答案 0 :(得分:0)

请仔细阅读评论。

JSFiddle

$(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);
});