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

And*_*ham 0 javascript

这感觉就像一个初学问题,有一个非常明显的答案,但我无法弄清楚我的生活.我在下面尝试创建一个新元素并将其添加到正文中有什么问题?

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";
Run Code Online (Sandbox Code Playgroud)

Dav*_*der 6

宽度和高度属性不适用于它们中的"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";
Run Code Online (Sandbox Code Playgroud)