我正在练习一些Javascript,而我正试图弄清楚如何将屏幕左侧的div移到右边。我在一个单独的文件中执行此操作以首先测试它并且它可以工作,但是,如果我创建一个类并将我的函数和变量放在其中停止工作并且Firebug不会给我任何错误。谁能帮我? 这是我想出的代码:
function crear_div (){
this.pos_x = 10;
this.pos_y = 10;
this.x_min = 10;
this.x_max = 500;
this.y_min = 10;
this.y_max = 500;
this.incremento = 10;
this.estado = 0;
this.id_elemento = "pelota";
this.f0 = f0;
this.f2 = f2;
}
function f0(){
this.pos_x = this.pos_x + this.incremento;
document.getElementById(this.id_elemento).style.left = this.pos_x + "px";
if (this.pos_x >= this.x_max){
this.estado = 1;
}
}
function f2(){
this.pos_x = this.pos_x - this.incremento;
document.getElementById(id_elemento).style.left = this.pos_x + "px";
if (this.pos_x <= this.x_min){
this.estado = 0;
}
}
function desplazar(){
switch(this.estado){
case 0:
this.f0();
break;
case 1:
this.f2();
break;
}
}
window.setInterval(function () {this.desplazar();}, 250);
答案 0 :(得分:0)
您需要创建类的对象,并在区间函数中使用它:
var the_div = new crear_div();
window.setInterval(function() {
the_div.desplazar();
}, 250);