Getboundingclientrect () method in JavaScript

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.