outerHeight(true)不包含边距?

时间:2013-10-07 22:23:01

标签: jquery html angularjs

根据JQuery docs outerHeight(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']);

在此示例中&lt; ul&gt; element使用默认样式添加16px的上下边距。这带来了&lt; ul&gt;的outerHeight了。至52px。

现在父母&lt; div&gt; element显示outerHeight(true)仅为20px - 不包括任何边距。

question on SO talks关于崩溃边距,我理解解释 - 在某种程度上。我的问题不是为什么不包括利润。

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

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

2 个答案:

答案 0 :(得分:11)

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

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

答案 1 :(得分:1)

您应单独计算没有边距的容器高度,然后在容器顶部+底部边距与第一个孩子的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/

相关问题