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