jQuery宽度不包括内部元素填充

jQuery width does not include inner element padding

本文关键字:元素 填充 内部 不包括 jQuery      更新时间:2023-09-26

当一个元素包含包含padding的inline-block时,它不会被包含在元素的宽度计算中。

本质上与父元素的jQuery outerWidth问题相同,该父元素有带padding的子元素。

这个页面应该有与绿色框右侧对齐的文本,然而,文本将永远比它的容器大,因为宽度从不包括它的任何子元素的填充。

是否有一种方法可以正确地找到元素的宽度,而无需手动枚举所有子元素并重新添加每个子元素的填充?使用.css('width').width().outerWidth()时,结果相同。

<html>
<head>
  <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
  <script>
    jQuery(document).ready(function() {
      var e = jQuery('#BLAH');
      var pw = e.parent().width();
      e.css('font-size','1px');
      if (e.outerWidth() < pw) {
        while ( e.outerWidth() < pw) {
          alert('width ' + e.outerWidth() + ' < ' + pw);
          e.css('font-size','+=1px');
        }
        e.css('font-size','-=1px');
      }
    });
  </script>
  <style>
    #BLAH {
      background-color: red;
      white-space: nowrap;
    }
    .BLAH {
      //padding: 0 10%;
      background-color: blue;
      display: inline;
    }
  </style>
</head>
<body>
    <div style="background-color: green; width: 50%; height: 50%">
      <div id="BLAH" style="display: inline-block;">
        <div class="BLAH">BLAH</div>
        <div class="BLAH">BLAH</div>
        <div class="BLAH">BLAH</div>
        <div class="BLAH">BLAH</div>
      </div>
    </div>
</body>
</html>

由于这个问题只发生在百分比填充上,你可以使用固定的像素填充,并在javascript中增加你的字体大小。像这样:

jQuery(document).ready(function () {
    var e = jQuery('#BLAH');
    var pw = e.parent().width();
    e.css('font-size', '1px');
    if (e.outerWidth() < pw) {
        while (e.outerWidth() < pw) {
            console.log('width ' + e.outerWidth() + ' < ' + pw);
            e.css('font-size', '+=1px');
            jQuery(".BLAH").css({
                'padding-right': '+=1px',
                'padding-left': '+=1px'
            });
        }
        e.css('font-size', '-=1px');
        jQuery(".BLAH").css({
            'padding-right': '-=1px',
            'padding-left': '-=1px'
        });
    }
});
http://jsfiddle.net/5Gufk/

如果你想让它更复杂,你可以计算填充父元素的前一个宽度的百分比,并应用它,而不是仅仅增加一个,或任何其他公式。


至于为什么它是这样工作的,我找不到CSS规范中定义这种行为的部分。然而,重要的是要理解填充百分比是基于包含块的宽度的。考虑一下如果你有6个元素,两边都有10%的填充,它会如何工作。那就是120%的内边距,元素的内边距是父元素宽度的120%怎么可能在父元素中还能放得下呢?