2016-07-26 9 views
1

Ich möchte zwischen einem Array von Hintergrundfarben animieren.jQuery Hintergrundfarbe animieren. Remove Math.random

Ich fand den folgenden Code, aber es verwendet Math.random, um die Hintergrundfarben in zufälliger Reihenfolge anzuzeigen.

$(document).ready(function() { 
    setInterval(function() { 
     var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff'); 
     var theColour = theColours[Math.floor(Math.random()*theColours.length)]; 
     $('#branding').animate({backgroundColor: theColour}, 500); 
    }, 1000); 
}); 

JSFiddle

Ich möchte die Math.random und die nächste Farbe in der Matrix entfernen.

Wenn ich jedoch Math.random mit dem folgenden ersetzen, wird die Animation nicht über die erste Farbe im Array fortgesetzt.

$(document).ready(function() { 
    setInterval(function() { 
     var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff'); 
     var currentColour = 0; 
     var theColour = theColours[Math.floor(currentColour++ % theColours.length)]; 
     $('#branding').animate({backgroundColor: theColour}, 500); 
    }, 1000); 
}); 

Antwort

1

Da currentColour in Ihrem setInterval Funktion deklariert wird, werden Sie eine neue currentColour Variable erstellen und zu 0 jedes Mal die Funktion aufgerufen wird Einstellung. Stattdessen currentColour außerhalb des Funktionsumfangs bewegen:

$(document).ready(function() { 
    var currentColour = 0; // This variable is now shared by each function call 
    setInterval(function() { 
     var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff'); 
     var theColour = theColours[Math.floor(currentColour++ % theColours.length)]; 
     $('#branding').animate({backgroundColor: theColour}, 500); 
    }, 1000); 
}); 
0

Das Problem ist, dass Sie wieder zu initialisieren ‚theColour‘ in den Code selbst.

$(document).ready(function() { 
var currentColour = 0; 
    setInterval(function() { 
     var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');    
     var theColour = theColours[Math.floor(currentColour++ % theColours.length)]; 
     $('#branding').animate({backgroundColor: theColour}, 500); 
    }, 1000); 
}); 
0

Sie müssen die currentColour aus Funktion setInterval

$(document).ready(function() { 
 
\t \t var currentColour = 0; 
 
    setInterval(function() { 
 
     var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff'); 
 
     var theColour = theColours[Math.floor(currentColour++ % theColours.length)]; 
 
     $('#branding').animate({backgroundColor: theColour}, 500); 
 
    }, 1000); 
 
});

definieren