获取元素的高度减去填充,边距,边框宽度 [英] Get the height of an element minus padding, margin, border widths

查看:107
本文介绍了获取元素的高度减去填充,边距,边框宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道当没有内联高度声明时,是否可以获得元素的高度(减去垂直填充,边框和边距)?我需要支持IE8及以上版本。

Does anyone know if it's possible to get just the height of an element (minus vertical padding, border, and margin) when there is no inline height declaration? I need to support IE8 and above.

el.style.height 在外部样式表中。

el.offsetHeight el.clientHeight 不工作,因为它们不仅包括元素的高度。我不能只是减去元素的填充等,因为这些值也设置在CSS样式表,而不是内联(因此 el.style.paddingTop doesn' t工作)。

el.offsetHeight or el.clientHeight doesn't work because they include more than just the element's height. And I can't just subtract the element's padding, etc. because those values are also set in a CSS stylesheet, and not inline (and so el.style.paddingTop doesn't work).

也不能做 window.getComputedStyle(el),因为IE8不支持。

Also can't do window.getComputedStyle(el) because IE8 doesn't support this.

jQuery有一个height()方法,它提供了这个,但是我没有在这个项目中使用jQuery,加上我只是想知道如何做到这一点纯JavaScript。

jQuery has the height() method, which offers this, but I'm not using jQuery in this project, plus I just want to know how to do this in pure JavaScript.

任何人都有什么想法?非常感谢。

Anyone have any thoughts? Much appreciated.

推荐答案

这里:

var style = window.getComputedStyle(document.getElementById("Example"), null);
style.getPropertyValue("height");

上述版本可在现代浏览器中使用。请检查currentStyle for IE浏览器。

The above version will work in modern browsers. Please check currentStyle for IE browsers.

跨浏览器:

try {
 el = window.getComputedStyle(document.getElementById('example'), null)
     .getPropertyValue('height');
} catch(e) {
 el = document.getElementById('example').currentStyle.height;
} 

这篇关于获取元素的高度减去填充,边距,边框宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆