This paper illustrates the method of the random handover of the background image of JS Web page. Share to everyone for your reference. The implementation methods are as follows:
First of all to prepare some images, the size of the image (whether size or data size) to control, if too large, users can not wait to see the whole picture jumped out, if too small, will affect the quality of the page
Make these images an array in script for easy invocation. The length of the array is, of course, the number of images.
Copy Code code as follows:
var bodybgs = []; Create an array variable to store the path of the background picture
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 it uses 5 images, you need to generate a random number from 0 to 4 here. If the array length is not the same, modify the multiplier in the following code.
Copy Code code as follows:
var randombgindex = Math.Round (Math.random () * 4);
The core process is these. Although very simple, but is a small idea, if on this basis, through processing can make some extension functions. For example: Theme switching and other random rendering, and so on. The following is the complete JS code.
Copy Code 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 this article will help you with your JavaScript based web design.