这确实很简单,但我不是程序员。我只是用一般的问题解决能力来暴力破解代码。这不适合这个。此代码设置为随机化背景图像,并且它有效。然而,它被设置为等到页面完全加载,所以它的时间太不一致了。据我了解, document.ready 会给我更一致(更快)的时间,但我似乎无法让它工作。这是工作版本:
<script type="text/javascript">
function changeImg(imgNumber) {
var myImages = [
"http://static.tumblr.com/0obftwk/u0Am8xfjf/streetarturbaninphilade.jpg",
"http://static.tumblr.com/0obftwk/Xmym8xfet/artmuseumarea.jpg",
"http://static.tumblr.com/0obftwk/znNm8xf9e/rowhouseswestphilly.jpg",
"http://static.tumblr.com/0obftwk/af1m8xf87/phillyvista.jpg",
"http://static.tumblr.com/0obftwk/ydIm8xf74/chinagatephiladelphia.jpg",
"http://static.tumblr.com/0obftwk/8kCm8xf41/broadritner.jpg"
];
var imgShown = document.body.style.backgroundImage;
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
}
window.onload=changeImg;
</script>
最佳答案
如果在加载页面之前已知图像列表,请将引用粘贴到 CSS 中的图像,然后只需更改 document.body 上的 className
.bgClass1 {background-image: url(http://static.tumblr.com/0obftwk/u0Am8xfjf/streetarturbaninphilade.jpg)}
...等等...
<body class="bgClass1">
否则,用js构建预加载器
关于javascript - 随机背景已准备就绪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12168472/