Home > Article > Web Front-end > Description of element dimensions (dimensions)_javascript skills
In the past, I memorized these attributes by rote and rarely really understood them. If I forgot, I would refer to the manual. After reading this article I believe this will never happen again.
The size of the physical space occupied by the element
If you need to get the physical space occupied by the element, then use offsetHeight and offsetWidth.
Naturally, this physical space must include: padding, scroll bars, and borders. These two properties are consistent with the height and width properties of getBoundingClientRect().
To help you understand, please look at the picture below:
The size of the visible area of the element content
The visible area includes padding, but does not include borders and scroll bars. . Please use clientHeight and clientWidth at this time.
To help understand, please look at the picture below:
The size of the entire content of the element
If you want to get the true size of the element content, of course it also includes those that are invisible content, you need to use scrollHeight/scrollWidth at this time.
For example, if a 600*400 picture is contained in a 300*300 scrollable container element, scrollWidth will return 600, and scrollHeight will return 400.
Actual measurement:
When the element has a scroll bar When the Chrome browser obtains the scrollHeight of an element, it is sometimes inaccurate! But the example in this article is correct, I don’t know how to reproduce it.
Get the real size of the element
In most scenarios, we don’t care about the size of the entire content of the element (except for window/document/body elements). The most commonly used one is probably to get the size occupied by the element. Physical space (offsetHeight/offsetWidth).
For example, to set a custom tooltip for a certain piece of text, you need to obtain the height of the target element and then position the tooltip.
Both clientHeight and offsetHeight contain padding. Assuming that this text contains 100px padding, the position of this tooltip will obviously be extremely inaccurate.
So getting the height of an element usually requires removing padding.
Since the style attribute of an element can only obtain the width/height of the inline style, you need to use el.currentStyle.height/width in IE.
And in standard browsers, use window.getComputedStyle(el,null ).width/height.
The following is a method I compiled for garden friend Snandy to get the real height and width of an element:
Determining the dimensions of elements
Measuring Element Dimension and Location with CSSOM in Internet Explorer 9