Javascript 使用setInterval移动某个div
我试图给Javascript 使用setInterval移动某个div,javascript,html,css,setinterval,Javascript,Html,Css,Setinterval,我试图给move()指定间隔,以便我的箱子可以在容器中移动,但它不起作用。我在内的主索引页中列出了我的box类,该类已初始化。该box已创建,但未移动 //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; //rando
move()
指定间隔,以便我的箱子可以在容器中移动,但它不起作用。我在
内的主索引页中列出了我的box类,该类已初始化。该box已创建,但未移动
//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);
}
}
//在容器中添加新框对象的类
功能盒(元件){
随机变量;
var随机性;
var-movex;
var movey;
this.element=元素;
var divi;
var=这个;
//随机数发生器
this.randomGenerator=功能(低、高){
var randomgen=Math.floor((Math.random()*高)+低);
返回随机数发生器;
}
//初始化变量
this.initial=函数(){
divi=document.createElement('div');
divi.className=“box”;
randomx=该随机发生器(0950);
randomy=that.randomGenerator(0350);
movex=that.random生成器(6,12);
movey=that.随机发生器(6,12);
var maine=该元素;
缅因州。佩德柴尔德(divi);
}
//检查长方体的边界的步骤
this.checkBoundary=函数(){
如果(随机数x>=(950)){
movex=-(即.randomGenerator(6,12));
控制台日志(“错误1”);
}
如果(随机数x=(350)){
movey=-(即随机生成器(6,12));
控制台日志(“错误3”);
}
if(randomy函数setInterval();
需要一个函数作为第一个参数:setInterval(function(){that.move();},10)
类框的位置与静态的位置不同吗?是的,每次我刷新页面时它都不同!我指的是css属性位置
。css类框
上是否设置了位置:相对的或位置:绝对的以及如何使用框
结构或者?你是在构建它之后调用init
?var randomgen=Math.floor((Math.random()*high)+low);
这不应该是var randomgen=Math.floor((Math.random()*(high-low))+low);
?谢谢它工作了,但是运动不是很平稳,你知道如何才能让它平稳吗?看看这篇帖子: