The JS implementation drags the sample code

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

GetBoundingClientRect () to get the location of the page element

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 / / 2013101171346 ">  
< img SRC = "border = 0 / / 2013101171435 ">  
Code example:
<span style="font-size:14px"><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> 
<html xmlns=""> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 

<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> 
document.getElementById('demo').onclick=function (){ 
if (document.documentElement.getBoundingClientRect) { 
<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) 

Related articles: