gpt4 book ai didi

JavaScript 尝试创建新元素不起作用

转载 作者:行者123 更新时间:2023-11-28 12:04:34 24 4
gpt4 key购买 nike

这感觉像是一个初学者问题,答案很明显,但我一生都无法弄清楚。我在下面尝试创建新元素并将其添加到正文时出现什么问题?

var newDiv = document.createElement("div");
newDiv.setAttribute("id", "popup");
newDiv.setAttribute("width", "400px");
newDiv.setAttribute("height", "400px");
newDiv.setAttribute("backgroundColor", "red");
document.getElementsByTagName("body")[0].appendChild(newDiv);
newDiv.style.position = "absolute";
newDiv.style.left = "25px";
newDiv.style.top = "25px";

最佳答案

宽度和高度属性不适用于其中的“px”,我也不确定背景属性。无论哪种方式,以下方法都有效,并且是您应该这样做的方式:

var newDiv = document.createElement("div");
newDiv.setAttribute("id", "popup");
newDiv.style.width="400px";
newDiv.style.height="400px";
newDiv.style.backgroundColor="red";
document.getElementsByTagName("body")[0].appendChild(newDiv);
newDiv.style.position = "absolute";
newDiv.style.left = "25px";
newDiv.style.top = "25px";

关于JavaScript 尝试创建新元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11367207/

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