2017-04-20 70 views
0

創建我試圖以編程方式創建乘法的div,並設置一個div的寬度別人寬,有點像這樣:無法獲取元素的寬度相同的功能

var container1 = document.createElement("div"); 
 
container1.style.width = "400px"; 
 
container1.appendChild(document.createElement("h1")); 
 
container1.getElementsByTagName("h1")[0].innerHTML = "Hello there!"; 
 
document.getElementById("frame").appendChild(container1); 
 

 
var container2 = document.createElement("div"); 
 
container2.style.width = container1.offsetWidth; 
 
container2.appendChild(document.createElement("h2")); 
 
container2.getElementsByTagName("h2")[0].innerHTML = "My width is " + container2.offsetWidth; 
 
document.getElementById("frame").appendChild(container2);
#frame div { 
 
    background-color: red; 
 
}
<div id="frame"></div>

爲什麼我不能得到元素的offsetWidth?有什麼我可能理解的錯誤是關於如何創建,插入和計算瀏覽器的元素?

預先感謝您!

+0

使用'後得到container2寬度clientWidth' – Ninjaneer

+0

我不知道如何我甚至在找到這個過程中失去了「px」。我現在覺得很愚蠢。 – Simon

回答

2

嘗試添加"px" affter寬度:

只能追加到html

var container1 = document.createElement("div"); 
 
container1.style.width = "400px"; 
 
container1.appendChild(document.createElement("h1")); 
 
container1.getElementsByTagName("h1")[0].innerHTML = "Hello there!"; 
 
document.getElementById("frame").appendChild(container1); 
 

 
var container2 = document.createElement("div"); 
 
container2.style.width = container1.offsetWidth + "px"; 
 
//          here ^^^^^^^ 
 
container2.appendChild(document.createElement("h2")); 
 
container2.getElementsByTagName("h2")[0].innerHTML = "My width is " + container2.offsetWidth; //Wont be able to get width here as you did not add to HTML yet! 
 
document.getElementById("frame").appendChild(container2); 
 
container2.getElementsByTagName("h2")[0].innerHTML = "My width is " + container2.offsetWidth;
#frame div { 
 
    background-color: red; 
 
}
<div id="frame"></div>

+0

謝謝!我改變了很多東西,最後我忘了添加「px」。對不起,沒有看到:) – Simon

+0

@Simon沒問題...快樂編碼..別忘了接受回答:) –

+0

@HarikrishnanN他忘了:D –