javascript - 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 中(上面的链接)。
解决方案
我对您的代码段做了一些更改。检查一下,如果您有任何疑问,请随时发表评论
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>
推荐阅读
- angular - Angular 5:我的回复不会覆盖默认属性
- prolog - Prolog - 运算符的绑定
- 3dsmax - 3ds Max中的阴影烘焙模糊
- installshield - Installshield:由于合并模块导致文件重复
- spring-boot - 多数据源配置的 Spring Boot 1.5.18 无法使用 HikariCP
- javascript - 如何等待 window.performance.timing 中的所有值都被定义
- xamarin - 使用 Environment 访问 Android 特殊文件夹路径
- python - matplotlib:多个子图未强制执行轴刻度标签对齐
- xcode - Xcode watch '无效的表达式'
- c# - XmlReader - 如何在没有 System.OutOfMemoryException 的情况下读取元素中很长的字符串