Today, a friend on the Weibo asked me if you can use JS and CSS to make every refresh of the page randomly generated a background picture, of course, my answer is yes. Specifically, you can do this:
1, use JS to define an image array, which stores the pictures you want to display randomly
Copy Code code as follows:
var imgarr=["Http://www.google.com.hk/intl/zh-CN/images/logo_cn.png",
"Yun_qi_img/baidu_sylogo1.gif",
"Yun_qi_img/20120111081906_79.jpg",
"Yun_qi_img/20120111081906_76.jpg"
];
Here I casually find 4 pictures, gather around alive to see.
2, with JS to generate a random number, of course, this random number from the beginning of 0 to Imgarr.length-1 end
Copy Code code as follows:
var index =parseint (Math.random () * (imgarr.length-1));
So we get the current randomly generated picture
Copy Code code as follows:
var currentimage=imgarr[index];
3, since a random generation of a background map, then use JS to this picture as a background map.
Copy Code code as follows:
document.getElementById ("Backgroundarea"). Style.backgroundimage= "url (" +currentimage+ ")";
Since this is a demo, I have defined a div with ID backgroundarea on the page, and also set a random background for this div.
Copy Code code as follows:
<div id= "Backgroundarea" >
</div>