Document.documentElement.getBoundingClientRect
Here's an explanation of MSDN:
Syntax
Orect = Object.getboundingclientrect () return Value
Returns a Textrectangle object. Each rectangle has four integer properties (top, left, right, and bottom) which represent a coordinate of the rectangle, in Pixels.
Remarks
This is retrieves an object that exposes the left, top, right, and bottom coordinates of the union of rectangles Relat Ive to the client ' s Upper-left corner. In Microsoft Internet Explorer 5, the window ' s upper-left are at 2,2 (pixels) With respect to true client.
Or, actually, this method gets the position of the left, top, right, and bottom of an element in the page relative to the browser window respectively. Also difficult to understand, the following illustrated with the figure.
This method is no longer the IE only, ff3.0+ and opera9.5+ have supported the method, can be said to get the page element position efficiency can be greatly improved, in the previous version of opera and Firefox must be through the loop to get elements in the absolute position of the page.
The following code has a simple example of scrolling through the red area of the scroll bar to see how the values change.
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <ptml xmlns=" http://www.w3.org/1999/xhtml "> <pead> <meta http-equiv=" Content-type "content=" text/html; charset=gb2312 "/> <title>Demo</title> </pead> <body > <div id=" Demo ">demo in order to facilitate the direct use of absolute Positioned elements </div> <script type= "Text/javascript" > document.getElementById (' demo '). onclick = function () {if (doc Ument.documentElement.getBoundingClientRect) {alert (' Left: ' + this.getboundingclientrect (). left); Alert ("Top:" + this.getboundingclientrect (). top); Alert ("Right:" + this.getboundingclientrect (). right); Alert ("bottom:" + this.getboundingclientrect (). bottom); var X = This.getboundingclientrect (). Left + Document.documentElement.scrollLeft; var Y = This.getboundingclientrect (). Top + Document.documentElement.scrollTop; Alert ("The location of the demo is x:" + x + "; Y: "+ y); }} </script> </body> </Html>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
With this approach, it's much simpler to get the page element's location,
var x= this.getboundingclientrect (). Left+document.documentelement.scrollleft;
var Y =this.getboundingclientrect (). Top+document.documentelement.scrolltop;
Current 1/2 page
12 Next read the full text