I have a web page with background image attached on body element I want to change background with a new image whenever the window is loaded so I wrote the following code but it is not working, I can't figure out as what I am missing.
JS:
window.onload = function(){
var bgdynamic = document.getElementById("bgdynamic");
var imgarray = new Array("bgs/bg_01.jpg", "bgs/bg_02.jpg", "bgs/bg_03.jpg", "bgs/bg_04.jpg", "bgs/bg_05.jpg", "bgs/bg_06.jpg", "bgs/bg_07.jpg");
var spot = Math.floor(Math.random()* imgarry.length);
bgdynamic.style.backgroundImage="url("+imgarray[spot]+")";
};
CSS:
body {
background-image: url(bgs/bg_01.jpg);
background-repeat: no-repeat;
background-size:cover;
}
HTML:
<body id="bgdynamic">
Content goes...
</body>
You missed a in
var spot = Math.floor(Math.random()* imgarry.length);
should be :
var spot = Math.floor(Math.random()* imgarray.length);`
我认为您在使用Math.random()时遇到问题,我认为这应该可以解决此问题:
var spot = (Math.Random() * imgarray.length) * 10
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.