This article introduces how to use JavaScript to obtain the location and size of DOM elements, if you have any need, you can refer to some complex pages that often use JavaScript to process the dynamic effects of some DOM elements. In this case, we often use the calculation of some element positions and sizes, browser compatibility is also a part of the problem that cannot be ignored. To write JavaScript code with the expected effect, we need to understand some basic knowledge.
Basic Concepts
To facilitate understanding, we need to understand several basic concepts. Each HTML element has the following attributes:
OffsetWidth |
ClientWidth |
ScrollWidth |
OffsetHeight |
ClientHeight |
ScrollHeight |
OffsetLeft |
ClientLeft |
ScrollLeft |
OffsetTop |
ClientTop |
ScrollTop |
To understand these attributes, we need to know that the actual content of the HTML element may be larger than the box allocated to hold the content, so the scroll bar may appear, and the content area is the viewport, when the actual content is larger than that of the viewport, the position of the element's scroll bar needs to be taken into account.
1. clientHeight and clientWidth are used to describe the inner size of an element. They are the content of an element + the size of the inner margin, excluding the border (actually included under IE), the outer margin, and the scroll bar.
2. offsetHeight and offsetWidth are used to describe the outer size of an element. They refer to the element content, padding, and border, excluding the outer margin and the scroll bar.
3. clientTop and clientLeft return the horizontal and vertical distance between the edge of the inner margin and the outer edge of the border, that is, the left and top Border width.
4. offsetTop and offsetLeft indicate the distance between the upper left corner (outer border edge) of the element and the upper left corner of the located parent container (offsetParent object ).
5. The offsetParent object refers to the relative (absolute) ancestor element of the element. It is recursively traced. If no ancestor element is located, null is returned.
Write a small example for ease of understanding
The Code is as follows:
The Code is as follows: