Home >Web Front-end >JS Tutorial >js getBoundingClientRect() to get the position of page elements_javascript skills
document.documentElement.getBoundingClientRect
Here is the explanation from MSDN:
Syntax
<em>oRect</em> = <em><span class="moreinfo" title="an element from the Applies To list below">object</span></em><strong>.getBoundingClientRect(</strong><strong>)</strong>
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.
To explain it in practice, this method obtains the left, top, right and bottom positions of an element on the page relative to the browser window. 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. You can scroll the scroll bar and click on the red area to see the changes in each value.