首页 > 解决方案 > JavaScript 构造函数/OOP

问题描述

我对javascript很陌生,我正在尝试重新创建它: https ://ibb.co/hh45jH

new Box(0, 0, 20, 30, "#007", parentDiv)

根本不产生任何东西,我不太清楚为什么。我希望它产生具有上述规格的彩色 div

到目前为止,这是我的代码:

class Box {
  constructor(xPosition, yPosition, width, height, backgroundColor, parentElement) {
    var div = document.createElement("div");
    div.style.width = width;
    div.style.height = height;
    div.style.background = backgroundColor;
    style.position = "absolute";
    style.top = yPosition;
    style.left = xPosition;
  }

  function draw() {
    var parent = document.getElementById("parentDiv");
    new Box(0, 0, 20, 30, "#007", parentDiv)
  }
}
window.addEventListener("load", draw);
.parentDiv {
  width: 500px;
  height: 500px;
  background-color: red;
}
<div class="parentDiv"></div>

我希望上面的 JavaScript 代码使用给定的指令(颜色、高度、宽度等)生成一个新的 div,然后像示例中一样将它放在 parentDiv 中(上面的链接)。

标签: javascript

解决方案


我对您的代码段做了一些更改。检查一下,如果您有任何疑问,请随时发表评论

class Box {
  constructor(xPosition, yPosition, width, height, backgroundColor) {
    this.element = document.createElement("div");
    var style = this.element.style;
    style.width = width + "px";
    style.height = height + "px";
    style.background = backgroundColor;
    style.position = "absolute";
    style.top = yPosition;
    style.left = xPosition;
  }
}

function draw() {
  let parentDiv = document.getElementById("parentDiv");
  let newBox = new Box(0, 0, 20, 30, "#557");
  parentDiv.append(newBox.element);
}


window.addEventListener("load", draw);
#parentDiv {
  width: 500px;
  height: 500px;
  background-color: red;
}
<div id="parentDiv"> asd </div>


推荐阅读