GetBoundingClientRect () to get the position of the page Element
Copy codeThe Code is as follows:
Document.doc umentElement. getBoundingClientRect
This method returns an object to obtain the position of an element on the left, top, right, and bottom of the page relative to the browser window, that is, the offset pixel value of the top, left, right, and bottom borders of the element relative to the upper left corner of the browser window (note, not the upper left corner of the document area. This method is no longer Internet Explorer Only. FF3.0 + and Opera9.5 + support this method. It can be said that the efficiency can be greatly improved in obtaining the page element location, therefore, getting the offset of an element on the page relative to the browser window becomes a useful place for getBoundingClientRect. According to an article, it's awsome, so handsome =. = Because you don't have to worry about offset, pagex, clientx, and so on. In earlier versions of Opera and Firefox, the absolute position of elements on the page must be obtained through loops.
Sample Code:
Copy codeThe Code is as follows:
<Span style = "font-size: 14px"> <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> Demo </title>
</Head>
<Body style = "width: 2000px; height: 1000px;">
<Div id = "demo" style = "position: absolute; left: 518px; right: 100px; width: 500px; height: 500px; background: # CC0000; top: 114px; "> Demo directly uses absolute positioning elements for convenience </div>
</Body>
</Html>
<Script>
Document. getElementById ('Demo'). onclick = function (){
If (document.doc umentElement. getBoundingClientRect ){
Alert ("left:" + this. getBoundingClientRect (). left)
Alert ("top:" + this. getBoundingClientRect (). top)
Alert ("right:" + this. getBoundingClientRect (). right)
Alert ("bottom:" + this. getBoundingClientRect (). bottom)
<Strong> var X = this.getboundingclientrect().left?document.doc umentElement. scrollLeft;
Var Y = this.getboundingclientrect().top?document.doc umentElement. scrollTop; </strong>
Alert ("the location of the Demo is X:" + X + "; Y:" + Y)
}
}
</Script> </span>