Get element location information: getboundingclientrect

Source: Internet
Author: User

A magic method.

I. History

Stealing a lazy, a transfer door: http://www.cnblogs.com/2050/archive/2012/02/01/2335211.html

II. Introduction

The Dom element method returns a textrectangle object, which contains the top, left, bottom, right, width, and height attributes, it indicates the four offsets of an element relative to the display area of the browser and the width and height of the element. They are all number, indicating the pixel value.

document.body.getBoundingClientRect().top      // 0document.body.getBoundingClientRect().width    // 600
Iii. Compatibility

The getboundingclientrect method first appeared in ie5 and was accepted by W3C as a standard. Currently, ie5.5 +, Firefox 3.5 +, chrome 4 +, Safari 4.0 +, opara 10.10 + and other browsers support this method, and the compatibility is almost perfect.

However, in earlier versions, browsers only have four attributes: Top, left, bottom, and right, without width and height. However, these two attributes can be calculated, so the compatible method can be written as follows:

var ro = object.getBoundingClientRect();var Top = ro.top;var Bottom = ro.bottom;var Left = ro.left;var Right = ro.right;var Width = ro.width||Right - Left;var Height = ro.height||Bottom - Top;
Iv. kiyou

Another similar method is getclientrects, but getboundingclientrect is enough.

Specific visible: http://blog.csdn.net/freshlover/article/details/8985887

V. Purpose

With scrolltop and scrollleft, you can get the location of the relative page:

var X = this.getBoundingClientRect().left+document.documentElement.scrollLeft;var Y = this.getBoundingClientRect().top+document.documentElement.scrollTop;

These two attributes have some compatibility issues, as shown in the following figure: http://www.cnblogs.com/purplefox2008/archive/2010/09/06/1818873.html

Get element location information: getboundingclientrect

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.