This article describes the method of randomly switching background images on JS. Share it for your reference. The specific implementation method is as follows:
First of all, you need to prepare some images. The size of the image (whether it is size or data size) must be controlled well. If it is too large, it will make the user unable to wait to view the full picture and jump out. If it is too small, it will affect the page quality.
Porce these images into an array in script for easy call. The length of the array is of course the number of images.
Copy the code as follows: var bodyBgs = []; //Create an array variable to store the path to 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 5 images are used above, a random number from 0 to 4 needs to be generated here. If the array length is different, just modify the multiplier in the following code.
The code copy 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 you use this as a basis, some extended functions can be made through processing. For example: topic switching and other random presentations, etc. Below is the complete JS code.
Copy the code as follows:<script type="text/javascript">
//<!CDATA[
var bodyBgs = [];
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";
var randomBgIndex = Math.round( Math.random() * 4 );
//Output a random background image
document.write('<style>body{background:url(' + bodyBgs[randomBgIndex] + ') no-repeat 50% 0}</style>');
//]]>
</script>
I hope that the description in this article will be helpful to everyone's web programming based on javascript.