简体   繁体   English

获取子元素的总宽度

[英]get total width of children elements

I have some HTML tags:我有一些 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 and #b have no css width attribute. #a#b没有 css 宽度属性。 How could I calculate the total width of container 's children elements in pixel?我如何计算container的子元素的总宽度(以像素为单位)?

Without jQuery, go this way:如果没有 jQuery,请这样做:

var children = document.getElementById('container').children;
var totalWidth = 0;

for (var i = 0; i < children.length; i++) {
    totalWidth += children[i].offsetWidth;
}

To check whether you need offsetWidth or something else see要检查您是否需要offsetWidth或其他内容,请参阅
Stackoverflow - Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively Stackoverflow - 分别理解 offsetWidth、clientWidth、scrollWidth 和 -Height

This code is shorter and use vanilla-js:此代码较短并使用 vanilla-js:

const el = document.querySelector('.some-el')
const totalWidth = Object.values(el.childNodes).reduce((total, i) => total + i.offsetWidth, 0)
console.log(totalWidth)

With jQuery, you can do it like this:使用 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);

 var totalWidth = 0; document.querySelectorAll('#container > *').forEach(function(child) { totalWidth += parseInt(child.offsetWidth, 10); }); console.log('Total Width: ', totalWidth);
 <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM