How to randomly change the background of a webpage using CSS in JS

Source: Internet
Author: User

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. Define An Image array in JS to store the images you want to randomly display.
Copy codeThe 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 four images and made a try.
2. Generate a random number using JS. Of course, the random number starts from 0 and ends with imgArr. length-1.
Copy codeThe Code is as follows:
Var index = parseInt (Math. random () * (imgArr. length-1 ));

In this way, we can obtain the currently randomly generated image.
Copy codeThe 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 codeThe Code is as follows:
Document. getElementById ("BackgroundArea"). style. backgroundImage = "url (" + currentImage + ")";

As this is a demo, I defined a div with the id of BackgroundArea on the page and set a random background for this div.
Copy codeThe Code is as follows:
<Div id = "BackgroundArea">
</Div>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.