【发布时间】:2016-02-29 17:12:33
【问题描述】:
我使用 setInterval 为动态创建的元素设置了动画。单击元素时,我希望它更改为随机方向(左、右、上或下)。
我认为问题是我不能将随机创建的方向传递给 setInterval 函数。
这里的html....
<div id="klicker"></div>
这里的 JavaScript .....
var box = document.getElementById("klicker");
var x = 1;
var startp = 200;
box.onclick = function() {
var newdiv = document.createElement('div');
document.body.appendChild(newdiv);
newdiv.style.width = 200 + 'px';
newdiv.style.height = 200 + 'px';
newdiv.style.backgroundColor = 'grey';
newdiv.style.position = 'absolute';
newdiv.style.left = startp + "px";
newdiv.style.top = startp + "px";
newdiv.setAttribute('id', 'runner')
var run = document.getElementById('runner');
var dire = 'right';
run.onclick = function() {
var mov = function() {
randoms();
};
function randoms() {
alert('ddddd');
var rnd = (Math.random() * 4) + 1; //ranom number 1-4
var rnd_down = Math.floor(rnd); //make it en integer
/*--- make each number a uniqe direction---*/
if (rnd_down == 1) {
dire = 'right';
} else if (rnd_down == 2) {
dire = 'left';
} else if (rnd_down == 3) {
dire = 'up';
} else {
dire = 'down';
}
};
var moveit = setInterval(function() {
movefunc();
}, 50);
function movefunc() {
/*----each direction will make the div travel in diffrent directions--*/
if (dire = 'right') {
x = x + 1;
newdiv.style.left = x + 'px';
} else if (dire = 'left') {
x = x - 1;
newdiv.style.left = x + 'px';
} else if (dire = 'up') {
x = x - 1;
newdiv.style.top = x + 'px';
} else {
x = x + 1;
newdiv.style.top = x + 'px';
}
};
};
}
【问题讨论】:
-
var dire范围仅在box.onclick处理程序内。它在movefunc中不可用。 -
第二次点击
box会生成一个带有重复id = 'runner'的div。 -
var newdiv范围仅在box.onclick处理程序内。它在movefunc中不可用。
标签: javascript random setinterval