Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
692 views
in Technique[技术] by (71.8m points)

javascript - Get the height of an element minus padding, margin, border widths

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 doesn't work because the styles are set in an external style sheet.

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's the solution that works for both cases of box-sizing: content-box and 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);

Works in IE9+

You can use feature detection

if (!getComputedStyle) { alert('Not supported'); } 

This will not work if element's display is inline. Use inline-block or use getBoundingClientRect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...