我正在尝试给move()
一个间隔,这样我的盒子就可以在一个容器中移动但是它不起作用。我列出了我的盒子类,它在<script>
内的主索引页面中初始化。盒子已经创建但是没有移动。
//class to add new box object in a container
function Box(element){
var randomx;
var randomy;
var movex;
var movey;
this.element = element;
var divi;
var that = this;
//random number generator
this.randomGenerator = function(low,high){
var randomgen = Math.floor((Math.random()*high)+low);
return randomgen;
}
//initializing the variables
this.initial = function(){
divi = document.createElement('div');
divi.className = "box";
randomx = that.randomGenerator(0,950);
randomy = that.randomGenerator(0,350);
movex = that.randomGenerator(6,12);
movey = that.randomGenerator(6,12);
var maine = that.element;
maine.appendChild(divi);
}
//to check for the boundary of the box
this.checkBoundary = function(){
if(randomx>=(950)){
movex =-(that.randomGenerator(6,12));
console.log("error1");
}
if(randomx<=0){
movex=(that.randomGenerator(6,12));
console.log("error2");
}
if(randomy>=(350)){
movey= -(that.randomGenerator(6,12));
console.log("error3");
}
if(randomy<=0){
movey=(that.randomGenerator(6,12));
console.log("error4");
}
}
this.move = function(){
divi.style["left"] = randomx + 'px';
divi.style["top"] = randomy + 'px';
that.checkBoundary();
randomx += movex;
randomy += movey;
console.log("randomx =",randomx);
console.log("randomy =",randomy);
}
//function to initialize other functions
this.init = function(){
that.initial();
setInterval(that.move(),10);
}
}
答案 0 :(得分:0)
函数setInterval();
期望函数作为第一个参数:setInterval(function() { that.move(); }, 10);
。