JavaScript试图创建一个新元素,但该新元素不起作用

JavaScript试图创建一个新元素,但该新元素不起作用,javascript,Javascript,这感觉像是一个初学的问题,答案很明显,但我一辈子都搞不懂。下面我尝试创建一个新元素并将其添加到主体中,有什么问题 var newDiv = document.createElement("div"); newDiv.setAttribute("id", "popup"); newDiv.setAttribute("width", "400px"); newDiv.setAttribute("height", "400px"); newDiv.setAttribute("backgroundCol

这感觉像是一个初学的问题,答案很明显,但我一辈子都搞不懂。下面我尝试创建一个新元素并将其添加到主体中,有什么问题

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";
设置newDiv.style.backgroundColor或设置属性style=background颜色:红色

高度和宽度相同


并且也放一些内容去看一些东西

我认为这是最好的方法

var newDiv = document.createElement("div");
newDiv.id = "popup";

newDiv.setAttribute("width", "400px");
newDiv.setAttribute("height", "400px");

newDiv.style.position = "absolute";
newDiv.style.top = "25px";
newDiv.style.left = "25px";
newDiv.style.backgroundColor = "red";

document.body.appendChild(newDiv);

没有什么我在Firebug中查看了它,一切似乎都很好,但实际上并没有出现。它位于页面上iframe内的HTML文档中。Body将div作为子对象,div的style属性将所有内容都设置为我想要的。背景色、宽度和高度应使用cssAlso设置,以防您不这样做,确保代码是在
主体
标记加载后运行的,而不是立即在
头部
中运行。只是一个简化:您可以使用
document.body
而不是
document.getElem…TagName('body')[0]
我建议最后添加。不管是哪种方式,很好的解释+1是的,我也考虑过追加,但不想将代码更改到超出最小值。您错过了
newDiv.setAttribute(“id”,“popup”)
witch会更好,只要
newDiv.id=“popup”
。宽度和高度可能需要作为属性,而不是样式。嗯,我听过很多关于这方面的争论,除了setAttribute(“name”)在IE上不起作用之外,我从来没有听过哪一个更好的结论性争论,所以我不想搞砸这一个。宽度和高度永远不应该是属性。永远不要,在最坏的情况下,你应该设置一个带有宽度和高度的样式属性。也需要设置宽度和高度。