Javascript 获取子元素的总宽度
我有一些HTML标签:Javascript 获取子元素的总宽度,javascript,jquery,width,measure,Javascript,Jquery,Width,Measure,我有一些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没有c
<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宽度属性。如何以像素为单位计算容器的子元素的总宽度?使用jQuery,可以这样做:
var width = 0;
$('#container').children().each(function () {
width += $(this).outerWidth();
// change to .outerWidth(true) if you want to calculate margin too.
});
console.log(width);
如果没有jQuery,请按以下方式操作:
var children = document.getElementById('container').children;
var totalWidth = 0;
for (var i = 0; i < children.length; i++) {
totalWidth += children[i].offsetWidth;
}
var children=document.getElementById('container').children;
var totalWidth=0;
对于(变量i=0;i
要检查是否需要offsetWidth
或其他内容,请参阅
此代码较短,并使用vanilla js:
const el = document.querySelector('.some-el')
const totalWidth = Object.values(el.childNodes).reduce((total, i) => total + i.offsetWidth, 0)
console.log(totalWidth)
我试过你的方法。但是,它没有计算#a
和#b
的默认宽度。请不要只发布代码作为答案,还要解释代码的作用以及如何解决问题。带有解释的答案通常更有帮助,质量更好,更容易吸引选票。