gpt4 book ai didi

javascript - 无法获取在同一函数中创建的元素的宽度

转载 作者:太空宇宙 更新时间:2023-11-04 01:50:52 24 4
gpt4 key购买 nike

我正在尝试以编程方式创建多个 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>

为什么获取不到Element的offsetWidth?关于浏览器如何创建、插入和计算元素,我可能理解有误吗?

提前致谢!

最佳答案

尝试在宽度后添加一个"px":

您只能在附加到 html 后获得 container2 宽度

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>

关于javascript - 无法获取在同一函数中创建的元素的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43516801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com