Home > Web Front-end > JS Tutorial > body text

Use js to operate css to implement js to change the background image example_javascript skills

WBOY
Release: 2016-05-16 16:56:01
Original
1116 people have browsed it

1. Use JS to define an image array, which stores the images you want to display randomly

Copy code The code is as follows:

ar imgArr=["http://www.jb51 .net/logo_cn.png",
"http://www.jb51.net/baidu_sylogo1.gif",
"http://www.jb51.net/news/uploadImg/20120111/20120111081906_79.jpg ",
"http://www.jb51.net/news/uploadImg/20120111/20120111081906_76.jpg"];

Please replace the above pictures with your own.

2. Use JS to generate a random number. Of course, this random number starts from 0 and ends at imgArr.length-1

Copy code The code is as follows:

var index =parseInt(Math.random()*( imgArr.length-1));

This way we get the current randomly generated image

Copy code The code is as follows:

var currentImage=imgArr[index];

3. Since a background image is randomly generated, use JS to use this image as the background image.

Copy code The code is as follows:

document.getElementById("BackgroundArea").style.backgroundImage ="url(" currentImage ")";

Since this is a demo, I defined a div with the ID BackgroundArea on the page, and also set a random background for this div.

Copy code The code is as follows:



Related labels:
js
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