This article mainly introduces how to implement random page switching of background images in Javascript, involving the calling techniques of arrays, random functions, and css styles, which is of great practical value, for more information about how to use JavaScript to randomly switch background images, see the following example. Share it with you for your reference. The specific implementation method is as follows:
First, you need to prepare some images. The image size (whether it is the size or data size) must be well controlled. If it is too large, the user will jump out after the user cannot wait to view the full image. If it is too small, the page quality is also affected.
Compile these images into an array in the script for easy calling. The length of the array is of course the number of images.
The Code is as follows:
Var bodyBgs = []; // create an array variable to store the path of the background image.
BodyBgs [0] = "images/01.jpg ";
BodyBgs [1] = "images/02.jpg ";
BodyBgs [2] = "images/03.jpg ";
BodyBgs [3] = "images/04.jpg ";
BodyBgs [4] = "images/05.jpg ";
Because five images are used above, a random number ranging from 0 to 4 is generated here. If the array length is different, modify the multiplier in the following code.
The Code is as follows:
Var randomBgIndex = Math. round (Math. random () * 4 );
These are the core programs. Although it is very simple, it is a small idea. If it is based on this, some expansion functions can be made through processing. For example, topic switching and other random presentations. The following is the complete JS Code.
The Code is as follows: