Home > Web Front-end > JS Tutorial > js method to randomly switch background images on web pages_javascript skills

js method to randomly switch background images on web pages_javascript skills

WBOY
Release: 2016-05-16 16:32:20
Original
2319 people have browsed it

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

First of all, prepare some images. The size of the image (whether it is size or data size) must be controlled well. If it is too large, the user will not be able to wait to see the whole image and jump out. If it is too small, it will affect the page quality.

Organize these images into an array in script for easy calling. The length of the array is of course the number of images.

Copy code The code is as follows:
var bodyBgs = []; //Create an array variable to store the background Image path
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 were used above, a random number from 0 to 4 needs to be generated here. If the array lengths are different, just modify the multiplier in the code below.

Copy 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 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 code The code is as follows:

I hope this article will be helpful to everyone’s web programming based on JavaScript.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template