Today, a friend asked me on weibo if I can use JS and CSS to make the page refresh randomly produce a background image every time I refresh it. Of course, my answer is OK. You can do this specifically:
1. Use JS to define an image array, which stores the pictures you want to display randomly
The code copy 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"
];
I found 4 pictures here and took a look.
2. Use JS to generate a random number, of course, this random number starts from 0 and ends from imgArr.length-1.
The code copy is as follows:
var index =parseInt(Math.random()*(imgArr.length-1));
This way we get the currently randomly generated image
The code copy is as follows:
var currentImage=imgArr[index];
3. Since a background image was randomly generated, use JS to use this image as the background image.
The code copy is as follows:
document.getElementById("BackgroundArea").style.backgroundImage="url("+currentImage+")";
Since this is a demo, I defined a div with the id of BackgroundArea on the page, and also set a random background for this div.
The code copy is as follows:
<div id="BackgroundArea">
</div>