简体   繁体   English

如何在考虑内部元素边缘的情况下获得DIV的高度?

[英]How to get the height of a DIV considering inner element's margins?

Consider de following markup: 考虑de跟随标记:

<div id="outerElement">
    <div id="innerElement" style="border: 1px solid blue; background-color: #f0f3f5; margin-top: 100px">  
        TESTE
    </div>
</div>

I want to get the actual final height of outerElement using javascript . 我想使用javascript获取outerElement的实际最终高度 I noticed that if I remove the vertical margins from innerElement I am able to get what I want but I cannot alter styles from within the outerElement . 我注意到如果我从innerElement删除垂直边距,我能够得到我想要的但我不能在outerElement改变样式。

How do I do this? 我该怎么做呢?

Obs: I already tried height, scrollheight and offsetHeight in all browsers. Obs:我已经在所有浏览器中尝试过height,scrollheight和offsetHeight。 Chrome gives me the expected value (including inner element's margins) for scrollHeight . Chrome为我提供了scrollHeight的预期值(包括内部元素的边距)。 All other browsers fail. 所有其他浏览器都失败

Add clearfix, use jquery height() and remove the clearfix class again. 添加clearfix,使用jquery height()并再次删除clearfix类。

That's gonna work. 那会好起来的。 : ) :)

I'd use jQuery. 我会用jQuery。 Try using 尝试使用

$("#myelementId").height()

And see if that does it. 看看是否这样做。

Try using clientHeight 尝试使用clientHeight

var outerElement = document.getElementById("outerElement");
if(outerElement.clientHeight) {
alert("Height is "+outerElement.clientHeight+"px");
}
else { alert("Old browser?"); }

I know what you're thinking... "this won't work!" 我知道你在想什么......“这不行!” and alas, it doesn't... but if you do something like add a border to outerElement ... even for just a moment... 唉,它没有...但是如果你做一些像添加边框到outerElement ...即使只是片刻......

var outerElement = document.getElementById("outerElement");
outerElement.style.border = "1px solid black";
var height = outerElement.clientHeight;
outerElement.style.border = "none";
alert("Height is "+height+"px");

Not the most beautiful solution but it works, and if you can figure out why it works (I sure as hell don't know :P) you might be closer to a good solution... 不是最美丽的解决方案,但它有效,如果你能弄清楚它为什么有效(我肯定不知道:P)你可能更接近一个好的解决方案......

Some older browsers may not support it though... you'd have to look into it; 一些较旧的浏览器可能不支持它...你必须调查它; I can't list 'em. 我不能列出他们。

you could use jQuery: 你可以使用jQuery:

$('#outerElement').height(); // gets the height of the div
$('#outerElement').outerHeight(); // gets the height of the div including margins and padding
$('#outerElement').innerHeight(); // gets the height of the div including padding

one of those is bound to work. 其中一个必然会起作用。

ok also not pretty but this is how I do it (disclaimer: I stole this from somewhere once) 好吧也不漂亮,但这是我的方式(免责声明:我从某处偷了这个)

var height = elem.clientHeight + getBufferHeight(elem, true);

function getBufferHeight(elem, includeMargins) {
    if (!elem.visible()) {
        return 0;
    }
    //do new Number instead of parseFloat to avoid rounding errors 
    var result = 0;
    if (includeMargins) {
        result =   
            new Number(elem.getStyle('marginTop').replace(/[^\d\.]/g, '')).ceil() +  
            new Number(elem.getStyle('marginBottom').replace(/[^\d\.]/g, '')).ceil();
    }     
    result +=
        new Number(elem.getStyle('borderBottomWidth').replace(/[^\d\.]/g, '')).ceil() +
        new Number(elem.getStyle('borderTopWidth').replace(/[^\d\.]/g, '')).ceil() +    
        new Number(elem.getStyle('paddingTop').replace(/[^\d\.]/g, '')).ceil() +
        new Number(elem.getStyle('paddingBottom').replace(/[^\d\.]/g, '')).ceil();                        
    return result;
}

This is a tricky question as what do you discern as the "appropriate" height. 这是一个棘手的问题,你认为什么是“适当的”高度。 The height of the content inside including borders, what about padding, or the actual margin use? 内部的内容高度包括边框,填充或实际边际使用情况? In general browser act fairly consistent on most things, but quirksmode can clear up what you need. 一般来说,浏览器在大多数事情上都表现得相当一致,但是quirksmode可以清除你需要的东西。 (As a hint, if you need the actual margin used, its gonna hurt). (作为提示,如果你需要使用实际的保证金,它会受到伤害)。

I guess you should go throw all element properties and the make a sum only in this way you can know the exactly height... but in the case of the height is set it by for example clear:both property I dont think is posible to know the heigth of an Element. 我猜你应该去抛出所有的元素属性,并且只有这样才能知道确切的高度...但是在高度的情况下它设置为例如clear:这两个属性我不认为是可行的知道元素的高度。

A 3 sec thought could be something like: 一个3秒的想法可能是这样的:

var o document.getElementById('id').style; var o document.getElementById('id')。style;

    var total = ((o.height.split("px")[0] == "") ? 0 : o.height.split("px")[0]) +
 ((o.marginTop.split("px")[0] == "") ? 0 : o.marginTop.split("px")[0]) + 
((o.marginBottom.split("px")[0] == "") ? 0 : o.marginBottom.split("px")[0]) + 
((o.paddingTop.split("px")[0] == "") ? 0 : o.paddingTop.split("px")[0]) +
    ((o.borderTop.split("px")[0] == "") ? 0 : o.borderTop.split("px")[0]) +
 ((o.borderBottom.split("px")[0] == "") ? 0 : o.borderBottom.split("px")[0])

But I guess you must include also the document.getElementById('id').height value if have it.... is thougth but can help.. 但我想你必须还包括document.getElementById('id')。高度值,如果它....是thougth但可以帮助..

best =) 最好=)

WARNING WARNING clientHeight almost works but doesn't include margins :( 警告警告clientHeight几乎可以工作,但不包括边距:(

Just thought I'd add that I've been trying this today, and while nahumsilva & plodder almost have it right (nahumsilva's version appears to be more cross-browser {plodder's doesn't appear to work in Chrome/WebKit, but I'm no expert on these things}), they've both missed that an element may have computed style elements that aren't defined by it's own style. 我想补充一点,我今天一直在尝试这个,虽然nahumsilva和plodder差不多正确(nahumsilva的版本看起来更像是跨浏览器{plodder's似乎不适用于Chrome / WebKit,但我'没有关于这些事情的专家}),他们都错过了一个元素可能已经计算出的风格元素没有被它自己的风格定义。

This was driving me nuts - I was wondering where my <p> elements were getting an extra 16px of margin height - until I realised it was coming from the computed style. 这让我疯了 - 我想知道我的<p>元素在哪里获得额外16px的边距高度 - 直到我意识到它来自计算出来的风格。

So, long story short, an approach like nahumsilva / plodder worked for me, with the added proviso that you should get the element's computed style with window.getComputedStyle( element, null ) , which returns a CSSStyleDeclaration object (like element.style ). 所以,长话短说,像nahumsilva / plodder这样的方法对我有用,附加条件是你应该使用window.getComputedStyle( element, null )来获取元素的计算样式,它返回一个CSSStyleDeclaration对象(如element.style )。 element.offsetHeight / element.clientHeight should give you the height without margins, so the whole thing looks like: element.offsetHeight / element.clientHeight应该给你没有边距的高度,所以整个事情看起来像:

var cstyle = window.getComputedStyle( element, null );
var elementHeight = element.offsetHeight +
Number( cstyle.marginBottom.replace(/[^\d\.]/g, '') ) +
Number( cstyle.marginTop.replace(/[^\d\.]/g, '') );

If you can set the outer div to style display : inline-block; 如果你可以将外部div设置为样式display : inline-block; then scrollHeight will include the margins of child elements. 然后scrollHeight将包含子元素的边距。

It will also work if you set style display : flex; 如果你设置样式display : flex;它也会工作display : flex; (supported by IE 9+) (由IE 9+支持)

这个答案可能有点明显,但如果您已经知道边距,为什么不手动将其添加到高度?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM