2016-03-24 6 views
1

Mit meinem Code, die "Lichter" schalten sich einzeln ein und dann eins nach dem anderen ausschalten, aber ich will dort nur eins sein Licht auf einmal. Ich möchte, dass das zuvor eingeschaltete Licht ausgeht, bevor das nächste eingeschaltet wird.Wie kann ich es so machen, dass ein Licht ausschaltet und dann kommt das andere auf

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

Antwort

0

Bitte lesen Sie auch die Kommentare.

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

Danke für die Hilfe Dehli. – JoshKerr

+0

@JoshKerr Gern geschehen. Wenn es Ihre Frage beantwortet hat, stellen Sie bitte sicher, es als die Antwort zu markieren. :) – Dehli

Verwandte Themen