gpt4 book ai didi

JavaScript 构造函数/OOP

转载 作者:行者123 更新时间:2023-12-03 02:01:00 25 4
gpt4 key购买 nike

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

新框(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>

关于JavaScript 构造函数/OOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50037295/

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