The JS implementation drags the sample code

  • 2020-03-26 21:46:08
  • OfStack

GetBoundingClientRect () to get the location of the page element
 
document.documentElement.getBoundingClientRect 

This method returns an object to get the left, top, right, and bottom positions of an element on the page relative to the browser window, that is, the offset pixel values of the top, left, right, and bottom boundaries of the element relative to the upper-left corner of the browser window (note, not the upper-left corner of the document area). And this method is no longer Only, IE FF3.0 + and Opera9.5 + has supported the method, can say to obtain page elements efficiency can be greatly improved, so get some element on the page relative to the offset of the browser window is getBoundingClientRect comes in, according to an article, it 's awsome, too handsome =. = because you don't have to worry about offset, pagex, clientx, etc. In previous versions of Opera and Firefox, you had to loop through to get the absolute position of the element on the page.
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201311/201311011713112.gif? 2013101171346 ">  
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201311/201311011714153.gif? 2013101171435 ">  
Code example:
 
<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 Use elements that are absolutely positioned directly for convenience </div> 
</body> 
</html> 
<script> 
document.getElementById('demo').onclick=function (){ 
if (document.documentElement.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.documentElement.scrollLeft; 
var Y = this.getBoundingClientRect().top+document.documentElement.scrollTop;</strong> 
alert("Demo The position is X:"+X+";Y:"+Y) 
} 
} 
</script></span> 

Related articles: