我正在尝试这样做,以便在访问或刷新页面时,背景会发生变化。我试图通过JS实现这一目标。
这是我目前拥有的JS:
<script type="text/javascript">
var imgCount = 3;
var dir = 'img/';
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
var images = new Array
images[1] = "1.png",
images[2] = "2.png",
images[3] = "3.png",
document.body.style.background = "url(" + dir + images[randomCount] + ")";
</script>
与HTML一起使用:
<html>
<head>
<!-- The JS was here but didnt liek to be pasted -->
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="page">
Rawr
</div>
</body>
</html>
CSS:
html, body {
background: no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
}
#page {
width: 900px;
height: auto;
border: #900 1px solid;
border-radius: 5px;
float: right;
margin-right: 20px;
}
我的主要问题是图像;首先 - 不要出现,其次 - 由于这个原因,我不知道脚本是否正常工作。
我的文件树就像根目录一样简单,文件夹名为'img',用于包含3张图片的图片,1 - 3是png的图片。
如果代码确实有效,请有人帮我确定背景未显示的原因。
感谢。对不起,如果我的帖子不合适,我真的不是最好的这种事情= /
答案 0 :(得分:0)
正如 adeneo 所说,你应该在DOM准备好之后放置你的脚本,比如
<强>更新强>
如果不重复背景,则应使用此代码段。
document.body.style.backgroundRepeat = "no-repeat";
完整代码
<html>
<head>
<!-- The JS was here but didnt liek to be pasted -->
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="page">
Rawr
</div>
<!-- put your script is here after dom is ready -->
<script type="text/javascript">
var imgCount = 3;
var dir = 'img/';
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
var images = new Array
images[1] = "1.png",
images[2] = "2.png",
images[3] = "3.png",
document.body.style.background = "url(" + dir + images[randomCount] + ")";
document.body.style.backgroundRepeat = "no-repeat";
//----^----for not repeat the background
</script>
</body>
</html>