How to get the height of a DIV considering inner e

2020-07-05 05:08发布

Consider de following markup:

<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. 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.

How do I do this?

Obs: I already tried height, scrollheight and offsetHeight in all browsers. Chrome gives me the expected value (including inner element's margins) for scrollHeight. All other browsers fail.

11条回答
萌系小妹纸
2楼-- · 2020-07-05 05:57

This answer may be a little obvious, but if you already know the margin, why not just manually add it to the height?

查看更多
混吃等死
3楼-- · 2020-07-05 06:06

you could use 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.

查看更多
女痞
4楼-- · 2020-07-05 06:07

Add clearfix, use jquery height() and remove the clearfix class again.

That's gonna work. : )

查看更多
5楼-- · 2020-07-05 06:10

Try using 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...

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...

Some older browsers may not support it though... you'd have to look into it; I can't list 'em.

查看更多
Anthone
6楼-- · 2020-07-05 06:10

If you can set the outer div to style display : inline-block; then scrollHeight will include the margins of child elements.

It will also work if you set style display : flex; (supported by IE 9+)

查看更多
登录 后发表回答