Js web page random switching background image method

  • 2020-03-30 04:15:46
  • OfStack

In this paper, the example of js to achieve the random switching of background images. Share with you for your reference. The specific implementation method is as follows:

The first thing to do is to prepare some images. The size of the images (both size and data size) should be controlled. If the image is too large, the user will not wait to see the full image, and if it is too small, the quality of the page will be affected

The images are encoded as an array in script for easy invocation. The length of the array is of course the number of images.

var bodyBgs = [];    //Creates 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";

Since there are five images used, we need to generate a random number from 0 to 4 here. If the array length is different, modify the multiplier in the code below.

var randomBgIndex = Math.round( Math.random() * 4 );

That's the core program. Although very simple, but it is a small idea, if based on this, through processing can make some extended functions. For example: theme switching and other random rendering and so on. Here is the complete JS code.

<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 random background
        document.write('<style>body{background:url(' + bodyBgs[randomBgIndex] + ') no-repeat 50% 0}</style>');
    //]]>
</script>


Related articles: