2013-10-07 23 views
5

根據JQuery docs outerHeight(true)函數返回包含填充邊框和邊距的元素的總高度。我遇到了這個承諾似乎被打破的案例。這是reproouterHeight(true)不包含頁邊距?

下面是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']); 

在這個例子中,<UL>元素使用默認的樣式,將16px的頂部和底部邊緣。這帶來了外部高度<ul>到52px。

現在父母<div>元素顯示outerHeight(true)只有20px - 它不包含任何邊距。

question on SO talks關於崩潰的利潤率,我理解的解釋 - 在一定程度上。我的問題不是爲什麼不包括利潤率。

我的問題是我如何確定渲染的div的高度。顯然outerHeight(真)在某些情況下是不正確的。

@Gaby:改變元素風格並不是唯一的方法來做到這一點。您還可以在前後添加0個高度塊項目。但我不想尋求一種防止邊緣崩潰的方法。我正在尋找一種通用的方法來確定元素佔據的總高度。我需要這個以避免限制使用我的ng-scroll指令。

回答

1

你應該分別計算無邊距容器高度,再放入容器頂部+底部邊緣和第一胎的邊距和最後孩子的保證金之和的最大值-底部。

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/

+1

這是非常有用的,但不幸的是在所有情況下不正確。看到你的小提琴的[this fork](http://jsfiddle.net/3v7t4tq0/)。我認爲你需要分別處理每個利潤率的崩潰。 – Danimal

+0

我想這個小提琴顯示正確的答案:http://jsfiddle.net/3v7t4tq0/ – Danimal

+0

對不起,我應該說這一個http://jsfiddle.net/14dsLo8h/ – Danimal