如何移动多个div框的背景?

Mar*_*ian 0 html javascript

在我的脚本中似乎有一个问题,我无法弄清楚它可能是什么......

这是JSfiddle

我正试图改变多个div框的背景.Evey生成第二个随机数,如果弹出正确的数字,则随机选择其中一个div并将其背景移位100px.如果该div上的背景已经移位,它将恢复到其原始状态.


JavaScript的


div = document.getElementById('time');
write = document.getElementsByClassName('write');
data = [0, 0, 0, 0];
setInterval(function () {
var num = Math.floor(Math.random() * 2);
div.innerHTML = num;
if (num == 1) {
    n = Math.floor(Math.random() * 4);
    if (data[n] = 0) {
        write[n].style.backgroundPosition = '0px 100px';
        data[n] = 1;
    } else {
        write[n].style.backgroundPosition = '0px 0px';
        data[n] = 0;
    }
}
}, 1000);
Run Code Online (Sandbox Code Playgroud)


CSS


.write {
    width: 100px;
    height: 100px;
    background: url('http://daokun.webs.com/back.png');
    -webkit-transition: all 1.5s cubic-bezier(.08, 1, .08, 1);
    float: left;
    margin-left: 10px;
}
Run Code Online (Sandbox Code Playgroud)


HTML


<div id="time"></div>
<div class="write"></div>
<div class="write"></div>
<div class="write"></div>
<div class="write"></div>
<script src="Construct.js"></script>
Run Code Online (Sandbox Code Playgroud)

Nat*_*pel 8

简单的错误

if (data[n] = 0) { // here you are always assigning the value 0 to data[n]
Run Code Online (Sandbox Code Playgroud)

应该

if (data[n] === 0) { // here you are actually comparing data[n] with the value 0
Run Code Online (Sandbox Code Playgroud)