【问题标题】:how to find real DIV height?如何找到真实的DIV高度?
【发布时间】:2016-12-07 20:07:04
【问题描述】:

我有以下html结构:

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

当我尝试使用 javascript 在 firefox 或 chrome div 中查找容器的高度时:

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

我得到了错误的 offsetHeight(如果与 clientHeight 一起使用)。 我只得到 H1 本身的高度,而不是元素周围的前边距/后边距。

有没有办法得到真实的高度?

【问题讨论】:

  • 如果你不能使用 jQuery,我也在我的答案中添加了纯 JS 解决方案

标签: javascript html height css offsetheight


【解决方案1】:

这是一个我认为对你有帮助的函数:

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
}

只要这样称呼它:

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

外部高度将在控制台中打印,但如果需要,您可以将其返回。

这是一个DEMO

【讨论】:

    【解决方案2】:

    我强烈推荐 JQuery 来做这些事情,但对于普通的 javascript,首先你必须得到你已经完成的 div 高度,然后分别获取边距和填充。
    就这样

            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);    
    

    编辑

    对不起,如果您执行“document.getElementById('container').style.marginTop”,它将返回带有“px”的值,因此您必须替换该值以删除“px”,然后解析 int。

    以上代码已修改

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 2010-09-17
      • 2011-08-12
      • 2013-02-16
      相关资源
      最近更新 更多