我尝试制作一个每秒随机移动,调整大小和更改div颜色的对象。
在我的经典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");
它有效一次,在我收到错误后#34;无法读取属性&#c;&#39;未定义&#34;。我试图以多种方式重写它,但我无法找到解决方案。
你能解释我的错误吗?
谢谢=)
答案 0 :(得分:2)
使用bind将this
变量设置为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");
因为执行上下文已更改
Set btn = ThisWorkbook.Sheets("Navigation").Buttons.Add(rng.Left, rng.Top, rng.Width, rng.Height * 2)