2012-07-06 65 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); 
相關問題