![](/img/trans.png)
[英]How to get element width/height with margin, padding, border in Native JavaScript (no jQuery)
[英]Get the height of an element minus padding, margin, border widths
有谁知道在没有内联高度声明的情况下是否可以只获得元素的高度(减去垂直填充、边框和边距)? 我需要支持IE8及以上。
el.style.height
不起作用,因为样式是在外部样式表中设置的。
el.offsetHeight
或el.clientHeight
不起作用,因为它们不仅仅包含元素的高度。 而且我不能只减去元素的填充等,因为这些值也是在 CSS 样式表中设置的,而不是内联的(因此el.style.paddingTop
不起作用)。
也不能做window.getComputedStyle(el)
因为 IE8 不支持这个。
jQuery 有 height() 方法,它提供了这个,但我没有在这个项目中使用 jQuery,而且我只想知道如何在纯 JavaScript 中做到这一点。
有人有什么想法吗? 非常感激。
这是适用于box-sizing
两种情况的解决方案: content-box
和border-box
。
var computedStyle = getComputedStyle(element);
elementHeight = element.clientHeight; // height with padding
elementWidth = element.clientWidth; // width with padding
elementHeight -= parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom);
elementWidth -= parseFloat(computedStyle.paddingLeft) + parseFloat(computedStyle.paddingRight);
适用于 IE9+
您可以使用特征检测
if (!getComputedStyle) { alert('Not supported'); }
如果元素的display
是inline
这将不起作用。 使用inline-block
或使用getBoundingClientRect
。
改进了 Dan 的代码以处理内联元素(使用offset*
而不是client*
):
var cs = getComputedStyle(element);
var paddingX = parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);
var paddingY = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom);
var borderX = parseFloat(cs.borderLeftWidth) + parseFloat(cs.borderRightWidth);
var borderY = parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth);
// Element width and height minus padding and border
elementWidth = element.offsetWidth - paddingX - borderX;
elementHeight = element.offsetHeight - paddingY - borderY;
element.getComputedStyle
将根据box-sizing
的值返回高度。 如果元素使用box-sizing: content-box;
,您可以使用getComputedStyle
计算没有填充或边框的高度:
var style = window.getComputedStyle(document.getElementById("Example"), null);
style.getPropertyValue("height");
上述版本将在现代浏览器中工作。 请检查 IE 浏览器的 currentStyle。
跨浏览器:
try {
el = window.getComputedStyle(document.getElementById('example'), null)
.getPropertyValue('height');
} catch(e) {
el = document.getElementById('example').currentStyle.height;
}
把丹的答案变成了一个函数
export const innerDimensions = (node) => {
var computedStyle = getComputedStyle(node)
let width = node.clientWidth // width with padding
let height = node.clientHeight // height with padding
height -= parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom)
width -= parseFloat(computedStyle.paddingLeft) + parseFloat(computedStyle.paddingRight)
return { height, width }
}
在IE8
尝试 element.currentStyle。 但请记住,不是borderRightWidth
(borderLeftWidth)
的回报而不是像素,但“薄”,“中”,“厚”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.