Home > Web Front-end > JS Tutorial > JS operation CSS randomly changes the background of the web page to achieve ideas_javascript skills

JS operation CSS randomly changes the background of the web page to achieve ideas_javascript skills

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

Today, a friend asked me on weibo if I could use JS and CSS to randomly generate a background image every time the page is refreshed. Of course, my answer is yes. Specifically, you can do this:
1. Use JS to define an image array, which stores the images you want to display randomly

Copy code The code is as follows:

var imgArr=["http://www.google.com.hk/intl/zh-CN/images/logo_cn.png",
"http: //www.baidu.com/img/baidu_sylogo1.gif",
"http://www.open-open.com/news/uploadImg/20120111/20120111081906_79.jpg",
"http:// www.open-open.com/news/uploadImg/20120111/20120111081906_76.jpg"
];

Here I randomly found 4 pictures to take a look at.
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));

In this way we get the current random generation 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:
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