gpt4 book ai didi

Javascript setInterval 不适用于此。对象

转载 作者:行者123 更新时间:2023-11-30 09:38:41 25 4
gpt4 key购买 nike

<分区>

我在使用 Javascript 中的 setInterval() 方法时遇到问题。我的主要类(class):

var sq1 = new Square(20, 20);
window.onkeydown = function (e)
{
var key = e.keyCode ? e.keyCode : e.which;
if (key == 38)
{
sq1.moveUp();
}
}

我有以下构造函数。

function Square(x,y)
{
var multiplicator = 10;

this.xPos = x;
this.yPos = y;

this.domObj = document.createElement("div");
this.domObj.style.position = "absolute";
this.domObj.style.left = this.xPos * multiplicator + 'px';
this.domObj.style.top = this.yPos * multiplicator + 'px';
this.domObj.style.width = multiplicator + 'px';
this.domObj.style.height = multiplicator + 'px';
this.domObj.style.backgroundColor = "black";
document.getElementById("idCanvas").appendChild(this.domObj);

this.moveUp = function ()
{
this.yPos--;
this.domObj.style.top = (this.yPos * multiplicator) + 'px';
}
}

现在一切正常,只需将每个 keyUp 事件向上 move 10px。但是我想在 keyUp 事件之后每 1000 毫秒自动调用 this.moveUp()。但是当我尝试这个时:

this.moveUp = function ()
{
setInterval(function ()
{
this.yPos--;
this.domObj.style.top = (this.yPos * multiplicator) + 'px';
}, 1000);
}

我收到“this”为空的错误。

我该如何修复它(最好不用 jQuery)?

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