我不知道我在这里失踪了什么,请你帮助我。
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>SNOW</title>
<meta charset="UTF-8">
</head>
<body>
<div id="snowDiv">*</div>
</body>
<script>
var SNOW = function () {
this.top = 0;
this.left = 0;
this.snowflake = document.getElementById('snowDiv');
this.snowflake.style.margin = this.top+'px 0px 0px '+this.left+'px';
this.snowflake.style.positon = 'absolute';
this.snowflake.style.zIndex = '1';
this.snowflake.style.position = 'absolute';
this.snowflake.style.height = '5px';
this.snowflake.style.width = '5px';
this.moveSnow = function () {
SNOW.top += 2;
SNOW.left += 5;
SNOW.snowflake.style.margin = SNOW.top+'px 0px 0px '+SNOW.left+'px';
window.requestAnimationFrame(SNOW.moveSnow);
};
};
var snowing = new SNOW();
snowing.moveSnow();
</script>
如果我将moveSnow函数放在SNOW对象之外它可以正常工作,但就像它没有那样。
答案 0 :(得分:0)
这是因为SNOW
引用了对象构造函数,而不是this
引用的实例。创建一个引用this
的变量,即that = this
。现在,您可以将方法应用于方法中的实例。
var SNOW = function () {
this.top = 0;
this.left = 0;
this.snowflake = document.getElementById('snowDiv');
this.snowflake.style.margin = this.top+'px 0px 0px '+this.left+'px';
this.snowflake.style.positon = 'absolute';
this.snowflake.style.zIndex = '1';
this.snowflake.style.position = 'absolute';
this.snowflake.style.height = '5px';
this.snowflake.style.width = '5px';
var that = this;
this.moveSnow = function () {
that.top += 2;
that.left += 5;
that.snowflake.style.margin = that.top+'px 0px 0px '+that.left+'px';
window.requestAnimationFrame(that.moveSnow);
};
};
var snowing = new SNOW();
snowing.moveSnow();
<div id="snowDiv">*</div>
答案 1 :(得分:0)
这是你的可变范围的问题.... 在这里查看jsbin链接... http://jsbin.com/keyaze/1/edit?html,output