我试图编写一个简单的随机数发生器,它会随机设置组的背景位置。
HTML:
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
CSS:
.button{
width: 100px;
height: 40px;
background:url(redMetal.jpg) no-repeat;
border: 1px solid #ff0000;
display: inline-block;
float: left;
margin: 20px;
text-align: center;
color: #fff;
}
使用Javascript:
var button = document.getElementsByClassName("button");
for (var i = 0; i < button.length; i++) {
x = Math.random() * (3499 - 0) + 0;
y = Math.random() * (2359 - 0) + 0;
button[i].style.backgroundPosition = (x * -1) + "px" + (y * -1) + "px";
button[i].innerHTML = i;
}
当我这样做时,我会在for循环的结束大括号之后得到一个UNCAUGHT SYNTAXERROR:意外的令牌ILLEGAL,我不明白为什么。