【问题标题】:get total width of children elements获取子元素的总宽度
【发布时间】:2014-06-24 14:59:06
【问题描述】:

我有一些 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 的子元素的总宽度(以像素为单位)?

【问题讨论】:

    标签: javascript jquery width measure


    【解决方案1】:

    使用 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);
    

    【讨论】:

    • 我试过你的方法。但是,它没有计算#a#b的默认宽度。
    【解决方案2】:

    没有jQuery,走这条路:

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

    要检查您是否需要offsetWidth 或其他内容,请参阅
    Stackoverflow - Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

    【讨论】:

      【解决方案3】:

      这段代码更短,使用 vanilla-js:

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

      【讨论】:

      • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
      猜你喜欢
      • 1970-01-01
      • 2015-10-25
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 2011-06-08
      • 1970-01-01
      • 2013-08-11
      相关资源
      最近更新 更多