Home >Web Front-end >JS Tutorial >Code for javascript getBoundingClientRect() to obtain the position of page elements [revised version] page 1/2_javascript skills
document.documentElement.getBoundingClientRect
Here is the MSDN explanation:
Syntax
oRect = object.getBoundingClientRect()Return Value
Returns a TextRectangle object. Each rectangle has four integer properties (top , left, right, and bottom) that represent a coordinate of the rectangle, in pixels.
Remarks
This method retrieves an object that exposes the left, top, right, and bottom coordinates of the union of rectangles relative to the client's upper-left corner. In Microsoft Internet Explorer 5, the window's upper-left is at 2,2 (pixels) with respect to the true client.
For practical explanation, this method obtains the value of an element on the page Left, top, right and bottom are the positions relative to the browser window respectively. It’s not easy to understand either, so I’ll explain it with a picture below.
This method is no longer IE Only. FF3.0 and Opera9.5 already support this method. It can be said that the efficiency of obtaining the position of page elements has been greatly improved. In previous versions of Opera and Firefox You must loop through to get the absolute position of the element on the page.
The following code gives a simple example. After scrolling the scroll bar, click the red area to see the changes in each value.