Pergunta

I'm working with the code below to change the background color of the div on button click. It chooses the colors randomly (math.random), but I'd like it to choose the colors in listed order (red > blue > yellow > etc.). Can anyone help me with this? Thanks in advance!

<style>
#changecolor2 {
    height: 100px;
    width: 100px;
}
</style>

<script>
var colors = ["red", "blue", "yellow", "green", "orange", "black", "cyan", "magenta"]
function changeColor() {
    var col = document.getElementById("changecolor");
    col.style.backgroundColor = colors[Math.floor((Math.random()*8)+1)];
}
</script>

<body>
<div id="changecolor2"></div>
<button onclick="changeColor();">change color</button>
</body>
Foi útil?

Solução

var colors = ["red", "blue", "yellow", "green", "orange", "black", "cyan", "magenta"];
var colorIndex = 0;
function changeColor() {
    var col = document.getElementById("changecolor2");
    if( colorIndex >= colors.length ) {
        colorIndex = 0;
    }
    col.style.backgroundColor = colors[colorIndex];
    colorIndex++;
}
window.onload = changeColor;

Fiddle : http://jsfiddle.net/aslancods/6S46U/

Outras dicas

Just maintain a variable that tracks the current color index. If it gets to the last color, simply go back to the first color.

var current = -1;
var colors = ["red", "blue", "yellow", "green", "orange", "black", "cyan", "magenta"]
function changeColor() {

    if(current > colors.length-1){
        current = 0;
    } else {
        current++;
    }

    var col = document.getElementById("changecolor");
    col.style.backgroundColor = colors[current];
}
<script type="text/javascript">
    var count = 0;
    var colors = ["red", "blue", "yellow", "green", "orange", "black", "cyan", "magenta"]
    function changeColor() {
        if(count >= colors.length-1){
            count = 0;
        } else {
            count++;
        }

        document.getElementById("changecolor2").style.backgroundColor = colors[count];
    }
</script>

This will help you and will be changing the background color in cyclic manner.

var colors = ["red", "green", "blue"];
var count = 0;
$(".button").click(function() {
    $("body").css("background-color", colors[count]);
    count++
    count >= colors.length ? count = 0: count ;
})
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top