我有以下html结构:
<div id="container">
<h1>This is an h1 element</h1>
</div>
当我试图找到在firefox或chromediv使用javascript的容器的高度:
var container = document.getElementById("container");
var offsetHeight = container.offsetHeight;
我得到错误的offsetHeight(也如果与clientHeight一起使用)。我只得到H1本身的高度,而不是元素周围的margin-before/margin-after。
有没有办法得到实际的高度?
这里有一个我认为会对你有帮助的函数:
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
我强烈推荐使用JQuery来做这些事情,但是对于普通的javascript,首先你必须获得div的高度,这你已经完成了,然后分别获得margin和padding。
就像这样
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。它将返回值为"px",所以你必须替换该值以删除"px",然后解析int。
以上代码修改