无法获取在同一函数中创建的Element的宽度

时间:2017-04-20 10:22:45

标签: javascript html css

我尝试以编程方式创建乘法div并将一个divs宽度设置为其他宽度,如下所示:



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>
&#13;
&#13;
&#13;

为什么我无法获得Element的offsetWidth?关于如何通过浏览器创建,插入和计算元素,我可能会理解错误吗?

提前谢谢!

1 个答案:

答案 0 :(得分:2)

尝试添加"px"宽度:

在追加到container2

后,您只能获得html宽度

&#13;
&#13;
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;
&#13;
#frame div {
  background-color: red;
}
&#13;
<div id="frame"></div>
&#13;
&#13;
&#13;