Getboundingclientrect ()
This method returns a rectangle object that contains four properties: Left, top, right, and bottom. Represents the distance between the edges of the element and the top and left sides of the page, respectively.
var Box=document.getelementbyid (' box '); Get element
Alert (Box.getboundingclientrect (). top); The distance from the top of the page to the top of the element
Alert (Box.getboundingclientrect (). right); Distance to the right of the element from the left side of the page
Alert (Box.getboundingclientrect (). bottom); The distance from the top of the page below the element
Alert (Box.getboundingclientrect (). left); Distance from left side of element to the left of the page
Note: IE, firefox3+, Opera9.5, Chrome, Safari support, in IE, the default coordinates are calculated from (2,2), resulting in a final distance of two pixels more than other browsers, we need to do a compatibility.
Document.documentElement.clientTop; Non-IE is 0,ie for 2
Document.documentElement.clientLeft; Non-IE is 0,ie for 2
Functionggetrect (Element) {
var rect = Element.getboundingclientrect ();
var top = Document.documentElement.clientTop;
var left= document.documentElement.clientLeft;
return{
Top:rect.top-top,
Bottom:rect.bottom-top,
Left:rect.left-left,
Right:rect.right-left
}
}
Add the margin, padding, borders, and scrollbars, respectively, to test whether all browsers are consistent.
Getboundingclientrect () method in JavaScript