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
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
var index =parseInt(Math.random()*(imgArr.length-1));
In this way we get the current random generation Image
var currentImage=imgArr[index];
3. Since a background image is randomly generated, use JS to use this image as the background image.
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.