简体   繁体   中英

Changing background color with Javascript not working properly

I have set an array of 5 colors that I want rotate/display as my background color every 5 seconds automatically. My Javascript code works however I don't understand how it displays the colors.

As you will see I want green to show first, then red, blue, orange and silver. In that order. However when I load the page it's completely random. For example it will show nothing when the page loads, then blue, red, blue, orange, red, silver, etc...completely random. Why is that and what am I doing wrong?

function changebackground() { 
var colors = ["green", "red", "blue", "orange", "silver"];

        setInterval(function() { 
            var bodyback = Math.floor(Math.random() * colors.length);
            var selectedcolor = colors[bodyback];
            document.body.style.background = selectedcolor;
        }, 5000);
    }
window.onload = changebackground();

you have a random function in here which is causing it

var bodyback = Math.floor(Math.random() * colors.length);
            var selectedcolor = colors[bodyback];

you will want to go through the array element by element

You are selecting a random index in your code:

var bodyback = Math.floor(Math.random() * colors.length);

Instead, you need to iterate through the possible indices, by storing a current index and incrementing it:

function changebackground() { 
    var colors = ["green", "red", "blue", "orange", "silver"];
    var curIndex = 0;

    setInterval(function() { 
        var selectedcolor = colors[curIndex];
        document.body.style.background = selectedcolor;
        curIndex = (curIndex + 1) % colors.length;
    }, 5000);
}
window.onload = changebackground();

Make sure you mod (%) the current index so that it resets to the beginning when you've reached the end of the array.

I would probably do something like this.

var colors=["green", "red", "blue", "orange", "silver"];
var bodyback=0;

setInterval(function(){
document.body.style.backgroundColor=colors[bodyback];
if(bodyback!=4){
   bodyback++;
}else{
   bodyback=0;}
},5000)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM