gpt4 book ai didi

javascript - 未捕获的TypeError : Cannot read property 'style' of undefined in object

转载 作者:行者123 更新时间:2023-12-03 08:55:22 27 4
gpt4 key购买 nike

我不知道我在这里想念的是什么,您能帮我吗?

这是我的代码:

<!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对象之外,则它可以工作,但不能那样。

最佳答案

这是因为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>

关于javascript - 未捕获的TypeError : Cannot read property 'style' of undefined in object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27581502/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com