Use JS to switch background images

The example of this article describes the method of js to realize the random switching of background images of web pages. Share it with everyone for your reference. The specific implementation method is as follows:

First of all, we need to prepare some images. The size of the image (whether it is the size or the data size) should be controlled well. If it is too large, the user will jump out without waiting to view the full image. If it is too small, it will affect the quality of the page.

These images are compiled into an array in the script, which is easy to call. The length of the array is of course the number of images.

 

Copy the code 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 5 images are used above, a random number from 0 to 4 needs to be generated here. If the array lengths are not the same, modify the multiplier in the code below.

 

Copy the 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 extended functions can be made through processing. For example: theme switching and other random presentations, etc. Below is the complete JS code.

 

Copy the code The code is 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 );
    //输出随机的背景图
        document.write('<style>body{background:url(' + bodyBgs[randomBgIndex] + ') no-repeat 50% 0}</style>');
    //]]>
</script>

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325372694&siteId=291194637