2012-07-06 69 views
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"; 
+0

究竟发生了什么? – 2012-07-06 17:48:56

+0

适用于我 - 出了什么问题? – Utkanos 2012-07-06 17:49:46

+0

没什么。我在Firebug中检查了一切,似乎一切都很顺利,但实际上并没有出现。它位于页面上的iframe中的HTML文档中。 Body将div作为一个孩子,div的style属性将所有设置设置为我想要的。 – 2012-07-06 17:50:08

回答

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"; 
+0

我会建议追加去最后。无论哪种方式,很好的解释+1 – lbstr 2012-07-06 17:52:15

+0

是的,我也想过追加,但不想将代码改变超出最低限度。 – 2012-07-06 17:53:15

+0

你错过了'newDiv.setAttribute(“id”,“popup”);'女巫会更好'newDiv.id =“popup”'。宽度和高度可能需要作为属性而不是风格。 – andlrc 2012-07-06 18:00:05

1

http://jsfiddle.net/4BBWj/2/ 任一组newDiv.style.backgroundColor或设置属性风格= backgreound色:红

同一高度和宽度。

并且还放了一些内容看东西。

+1

还需要为宽度和高度做到这一点。 – 2012-07-06 17:53:05

+0

哦是的。感谢您的纠正。 – Birey 2012-07-06 17:53:52

0

这是我认为最好的方法。

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); 
相关问题