当没有内联高度声明时,是否有人知道是否可以获得元素的高度(减去垂直填充,边框和边距)?我需要支持IE8及以上版本.
el.style.height
不起作用,因为样式是在外部样式表中设置的.
el.offsetHeight
或者el.clientHeight
不起作用,因为它们不仅仅包含元素的高度.而且我不能只减去元素的填充等,因为这些值也是在CSS样式表中设置的,而不是内联的(因此el.style.paddingTop
不起作用).
也做不到window.getComputedStyle(el)
因为IE8不支持这个.
jQuery有height()方法,它提供了这个,但是我没有在这个项目中使用jQuery,而且我只是想知道如何在纯JavaScript中执行此操作.
有人有什么想法?非常感激.
Dan*_*Dan 55
这是适用于以下两种情况的解决方案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);
Run Code Online (Sandbox Code Playgroud)
适用于IE9 +
您可以使用特征检测
if (!getComputedStyle) { alert('Not supported'); }
Run Code Online (Sandbox Code Playgroud)
如果元素display
是,这将不起作用inline
.使用inline-block
或使用getBoundingClientRect
.
Sal*_*bas 14
改进了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;
Run Code Online (Sandbox Code Playgroud)
干得好:
var style = window.getComputedStyle(document.getElementById("Example"), null);
style.getPropertyValue("height");
Run Code Online (Sandbox Code Playgroud)
以上版本适用于现代浏览器.请检查IE浏览器的currentStyle.
跨浏览器:
try {
el = window.getComputedStyle(document.getElementById('example'), null)
.getPropertyValue('height');
} catch(e) {
el = document.getElementById('example').currentStyle.height;
}
Run Code Online (Sandbox Code Playgroud)
把丹的答案变成了一个函数
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 }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
51122 次 |
最近记录: |