2015-10-28 32 views
0

我尝试制作一个对象,每秒随机移动一个div,调整其大小并更改其颜色。对象JavaScript,无法读取未定义的属性...之前只读

在我的古典HTML页面有

<div id="Rectangle1"></div> 

这里是我的代码

var colors = ["red","yellow","blue","dark","green","pink","purple"]; 

function Rectangle(tag){ 

    this.moveNShape = function() { 
     //Defining new values 
     this.width = Math.floor(Math.random()*250)+50; 
     this.height = Math.floor(Math.random()*250)+50; 
     this.x = Math.floor(Math.random()*400)+100; 
     this.y = Math.floor(Math.random()*400)+100; 
     this.color = colors[Math.floor(Math.random()*7)]; 
     //Update the view 
     this.tag.css("position","absolute").css("height",this.height).css("width",this.width).css("left",this.x).css("top",this.y); 
     this.tag.css("backgroundColor",this.color); 
     //Launch again 
     setTimeout(this.moveNShape,1000); 

    } 

    this.tag = $('#'+tag); 
    this.moveNShape(); 

} 

var rect1 = new Rectangle("Rectangle1"); 

它的工作原理一次后,我得到错误“无法读取的未定义的属性‘CSS’”。我试图用很多方式重写它,但我找不到解决方案。

你能解释我的错误吗?

谢谢=)

+0

哪条线是你收到的错误?你有几个电话到'.css'。 – ssube

回答

2

使用bindthis变量设置为Rectangle对象。

你得到这样的错误之前当moveNShape被称为经setTimeout究其原因,this成为window,因为执行环境发生了变化

var colors = ["red","yellow","blue","dark","green","pink","purple"]; 

    function Rectangle(tag){ 

     this.moveNShape = function() { 
      //Defining new values 
      this.width = Math.floor(Math.random()*250)+50; 
      this.height = Math.floor(Math.random()*250)+50; 
      this.x = Math.floor(Math.random()*400)+100; 
      this.y = Math.floor(Math.random()*400)+100; 
      this.color = colors[Math.floor(Math.random()*7)]; 
      //Update the view 
      this.tag.css("position","absolute").css("height",this.height).css("width",this.width).css("left",this.x).css("top",this.y); 
      this.tag.css("backgroundColor",this.color); 
      //Launch again 
      setTimeout(this.moveNShape.bind(this),1000); 

     } 

     this.tag = $('#'+tag); 
     this.moveNShape(); 

    } 

    var rect1 = new Rectangle("Rectangle1"); 
相关问题