首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我怎样才能让一个灯熄灭,然后另一个灯亮起来。

我怎样才能让一个灯熄灭,然后另一个灯亮起来。
EN

Stack Overflow用户
提问于 2016-03-24 15:27:49
回答 1查看 69关注 0票数 1

用我的代码,“灯”一次开一个,然后一次关一个灯,但我想一次只开一个灯。我想在下一个灯亮之前关掉以前的灯。

http://jsfiddle.net/JoshKerr98/hrpasw0p/

代码语言:javascript
复制
$(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);
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-24 15:40:42

请阅读评论。

JSFiddle

代码语言:javascript
复制
$(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);
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36203939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档