First you have a div that adds a background image
<div id= "Mydiv" ></div>
Add background tu to CSS styles
body{height:100%;}
#myDiv {background-image:url ("img/yellow.jpg"); height:100%;} Note that the added background map must be set to a specific numeric height to display, and here with 100% is not possible to display, which requires the parent of this div (in this case, the body) set height:100%. And then set it to 100%. is effective. And the height is full screen.
JS Code:
var Currentimg=math.floor (Math.random ()); That is, let currentimg get 0-3 random values between, can I equals, 0 and 3, this is used to take the image of the index subscript.
var imgarr=[' orange.jpg ', ' green.jpg ', ' yellow.jpg '];//define an array to hold all the pictures
function changeimg () {
var Img=document.getelementbyid ("Mydiv");
Img.style.backgroundimage= "url (img/" +img[currentimg]+ ")"; It is particularly important to note the use of quotes, because IMG[CURENTIMG] is a variable, so use "+ variable +"
}
And finally execute this function.
Changeimg ();
The above is each time you open the page or refresh will be randomly selected in three pictures.
If you want to change one at a time, just change JS to:
var currentimg=0; This is used to take the index of the image subscript.
var imgarr=[' orange.jpg ', ' green.jpg ', ' yellow.jpg '];//define an array to hold all the pictures
function changeimg () {
if (currentimg>=imgarr.length) {currentimg=0}//When the index of a picture exceeds the number of pictures, start with the first
else{currentimg++;}
var Img=document.getelementbyid ("Mydiv");
Img.style.backgroundimage= "url (img/" +img[currentimg]+ ")"; It is particularly important to note the use of quotes, because IMG[CURENTIMG] is a variable, so use "+ variable +"
}
It's a little different at the back, you need setinterval.
SetInterval (changeimg,400);//change one every 400ms
-------------------------------------
Add:
Math.random () Yes (0, 1)
Math.random () is (0,3)
Math.random () *3+1 Yes (1,4)
Math.floor (Math.random () *3+1) is [1,4] can be equal to 1,4 math.floor () is rounded down
So there are two ways to get the image index: 1.var currentimg=math.floor (Math.random ()); And take this currentimg directly.
2, let him 0 start add, add to the same length or longer than the length of the beginning of 0.
JS implementation of the background map on time to switch or update each time