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>