【问题标题】:outerHeight(true) does not include margins?outerHeight(true) 不包括边距?
【发布时间】:2013-10-14 16:12:31
【问题描述】:

根据JQuery docsouterHeight(true) 函数返回元素的总高度,包括填充边框和边距。我遇到了这个承诺似乎被打破的案例。这是repro

这里是html:

outer div height = <span id="div-target"></span><br/>
ul height (including margins) = <span id="ul-target"></span><br/><br/>
<div show-height-in='div-target'>
    <ul show-height-in='ul-target'>here</ul>
</div>

和javascript:

var app = angular.module('application',[]);
app.directive('showHeightIn', function($log){
    return function(scope, element,attrs) {
        $('#' + attrs.showHeightIn).text($(element).outerHeight(true));
    }
});
angular.bootstrap(document, ['application']);

在本例中,

    元素使用添加 16px 顶部和底部边距的默认样式。这会将
      的 outerHeight 设置为 52px。

      现在父

      元素仅显示 outerHeight(true) 20px - 不包括任何边距。

      这个question on SO talks 是关于折叠边距的,我理解这个解释 - 在一定程度上。我的问题不是为什么不包括边距。

      我的问题是如何确定呈现的 div 的高度。显然,在某些情况下,outerHeight(true) 是不正确的。

      @Gaby:改变元素样式并不是唯一的方法。您还可以在前后添加 0 高度的块项目。但我不是在寻找一种方法来防止边距崩溃。我正在寻找一种通用方法来确定元素占据的总高度。我需要这个来避免限制我的 ng-scroll 指令的使用。

      【问题讨论】:

    标签: jquery html angularjs


    【解决方案1】:

    div 元素上添加overflow:auto 将禁用边距折叠,并且将正确计算该值。

    演示地址 http://jsfiddle.net/hdReR/2/

    【讨论】:

      【解决方案2】:

      你应该单独计算没有边距的容器高度,然后将容器顶部+底部边距与first-child的margin-top和last-child的margin-bottom之和的最大值相加。

      var mVert = parseInt($('#container').css('margin-top'))
          + parseInt($('#container').css('margin-bottom'));
      var mVertChildren = parseInt($('#container').children().first().css('margin-top'))
          + parseInt($('#container').children().last().css('margin-bottom'));
      
      var realHeight = $('#container').outerHeight(false)
          + (mVert > mVertChildren ? mVert : mVertChildren);
      

      演示地址 http://jsfiddle.net/j67phdpd/2/

      【讨论】:

      • 这确实很有用,但不幸的是并非在所有情况下都正确。请参阅您的小提琴的this fork。我认为您需要单独处理每个边距崩溃。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-20
      • 2012-08-26
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多