简体   繁体   English

如何找到实际的DIV高度?

[英]how to find real DIV height?

I have the following html structure: 我有以下html结构:

<div id="container">
     <h1>This is an h1 element</h1>
</div>

When I try to find the height of the container in firefox or chrome div using javascript: 当我尝试使用javascript在firefox或chrome div中查找容器的高度时:

var container = document.getElementById("container");
var offsetHeight = container.offsetHeight;

I get the wrong offsetHeight (also if used with clientHeight). 我得到了错误的offsetHeight(如果与clientHeight一起使用)。 I get only the height of the H1 itself and not the margin-before/margin-after that surround the element. 我只得到H1本身的高度,而不得到元素周围的边距。

is there any way to get the real height? 有什么办法可以得到真实的身高吗?

Here's a function that I think will help you: 我认为以下功能可以为您提供帮助:

function outerHeight(elem){
    var curStyle = elem.currentStyle || window.getComputedStyle(elem);
    outerHeight = elem.offsetHeight;
    outerHeight += parseInt(curStyle.marginTop);
    outerHeight += parseInt(curStyle.marginBottom);

    console.log(outerHeight);
    //return outerHeight //If you'd like to return the outerheight
}

Just call it like this: 只是这样称呼它:

<div onclick="outerHeight(this)" id="container">
    <h1>This is an h1 element</h1>
</div>

The outer height will be printed in the console, but you can just return it if need be. 外部高度将打印在控制台中,但是您可以根据需要将其返回。

Here's a DEMO 这是一个演示

I highly recommande JQuery to do these kinda things but for normal javascript, first you have to get the div height, which you already done, then get the margin and padding separately. 我强烈建议JQuery做这些事情,但对于普通的javascript,首先必须获取已经完成的div高度,然后分别获取边距和填充。
Just like this 像这样

        var container = document.getElementById("container");
        var offsetHeight = container.offsetHeight;

        var a = parseInt(offsetHeight);
        var c = parseInt(container.style.marginTop.replace("px", ""));
        var d = parseInt(container.style.marginBottom.replace("px", ""));
        var e = parseInt(container.style.paddingTop.replace("px", ""));
        var f = parseInt(container.style.paddingBottom.replace("px", ""));

        var g = a +  c + d + e + f;
        alert(g);    

EDIT 编辑

Sorry if you do "document.getElementById('container').style.marginTop" it will return the value with "px", so you have to replace the value to remove the "px", then parse int. 抱歉,如果您执行“ document.getElementById('container')。style.marginTop”,它将返回带有“ px”的值,因此您必须替换该值以删除“ px”,然后解析int。

Code above modified 上面的代码已修改

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

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