【问题标题】:My DOM object will not update after my data updates in JavaScript在 JavaScript 中更新数据后,我的 DOM 对象不会更新
【发布时间】:2014-12-29 02:36:30
【问题描述】:

我有这个正方形,用构造函数创建,我的所有数据都会更新,包括它的 .style.top 和 .style.left,但它不会在页面上更新(图片)。这是我的代码,我省略了构造函数本身,因为它可能不是问题所在。我已经包含了构造函数的方法和方法的调用,不会更新图片。

  KeyBlock.prototype.move = function(event) {
  if(event.keyCode == 37)
    this.x -= 10;
  if(event.keyCode == 38)
    this.y -= 10;
  if(event.keyCode == 39)
    this.x += 10;
  if(event.keyCode == 40)
    this.y += 10;
  if (this.y < 0)
    this.y = 0;
  if (this.x < 0)
    this.x = 0;
  this.character.style.left = String(this.x) + "px";
  this.character.style.top = String(this.y) + "px";
  console.log(this.character.style.left);
}

me = new KeyBlock("me");
addEventListener("keyup", KeyBlock.prototype.move.bind(me));

如果你想看构造函数,可以在这个问题上找到,但可能不需要回答这个问题:Event Handler function in prototype's method, why does it think .keyCode is a property of undefined in JavaScript?

提前感谢:)

【问题讨论】:

  • 您的代码中的this.character 是什么?
  • @jfriend00,this.character 是在原始构造函数中定义的,它是保存 div 对象的属性,您可以在我的问题的链接中访问构造函数的代码。

标签: javascript dom methods


【解决方案1】:

在您在此问题或链接构造函数中显示的代码中,您没有为您的角色提供position 样式值。为了让style.left 和style.top 执行任何操作,您必须将style.position 值设置为默认值static 以外的值。


仅供参考,当您将数字添加到字符串时,您无需手动将内容转换为字符串(该数字将被自动转换)。所以不要这样:

this.character.style.left = String(this.x) + "px";

你可以这样做:

this.character.style.left = this.x + "px";

【讨论】:

  • 非常感谢@jfriend00,我忘了那一步
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
  • 2017-08-17
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多