我有一些 HTML 标签:
<div id="container">
<input type="text" id="a">
<textarea id="b"></textarea>
<div id="c" style="width:200px"></div>
<div id="d" style="width:20%"></div>
</div>
#a
和 #b
没有 css 宽度属性。如何计算 container
子元素的总宽度(以像素为单位)?
最佳答案
如果没有 jQuery,请这样做:
var children = document.getElementById('container').children;
var totalWidth = 0;
for (var i = 0; i < children.length; i++) {
totalWidth += parseInt(children[i].offsetWidth, 10);
}
要检查您是否需要 offsetWidth
或其他内容,请参阅
Stackoverflow - Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively
关于javascript - 获取子元素的总宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23521086/