Home>

The most commonly used control in html is the div, so how to get the coordinates of the div?

The following methods can be implemented:

/***
 * Get the coordinates of the div
 * @param divobj
 * @returns {{width:number, height:number, left:*, top:window}}
 * /
com.whuang.hsj.divcoordinate=function (divobj) {
  if (typeof divobj == "string") {
    divobj=com.whuang.hsj. $$id ("divobj");
  }
  return {"width":divobj.offsetwidth, "height":divobj.offsetheight,    "x":divobj.offsetleft, "y":divobj.offsettop,    "scrollleft":com.whuang.hsj.getscroll (). left, "scrolltop":com.whuang.hsj.getscroll (). top};
}
//cross browser gets the position of scroll
com.whuang.hsj.getscroll=function () {
  return {
    top:document.documentelement.scrolltop || document.body.scrolltop,    left:document.documentelement.scrollleft || document.body.scrollleft
  }
}

com.whuang.hsj.divcoordinate () method introduction

Function:Returns the div coordinates;

Parameters:id (string) of div object or div;

Return value:Object with six attributes:

width:the width of the div itself;

height:the height of the div itself;

x:coordinate x of the upper left corner of the div;

y:coordinate y of the upper left corner of the div;

scrollleft:the position of the horizontal scroll bar

scrolltop:the position of the vertical scroll bar

Test page:

<html>
<head lang="en">
  <meta charset="utf-8">
  <title></title>
  <script type="text/javascript" src="js/jquery-1.10.1.js"></script>
  <script type="text/javascript" src="js/common_util.js"></script>
  <script type="text/javascript">
  function run () {
      var loc=com.whuang.hsj.divcoordinate ("divobj");
//document.writeln ();
      com.whuang.hsj. $$id ("text22"). innerhtml="width:" + loc.width + ", height:" + loc.height + ", scrolltop:" + loc.scrolltop + ", scrollleft:" + loc .scrollleft + ", x:" + loc.x + ", y:" + loc.y;
    }
  </script>
</head>
<body>
<div>
</div>
<br>
<input type="button" value="run" onclick="run ();">
<div>
  </div>
</body>
</html>

operation result:

  • Previous Application examples of Python parsing XML through DOM and SAX
  • Next Android programming method for SD card to read database