Home >Web Front-end >JS Tutorial >js实现获取div坐标的方法_javascript技巧

js实现获取div坐标的方法_javascript技巧

WBOY
WBOYOriginal
2016-05-16 15:31:561605browse

本文实例讲述了js实现获取div坐标的方法。分享给大家供大家参考,具体如下:

html中最常使用的控件就是div了,那么如何获取div的坐标呢?

如下方法可以实现:

/***
 * 获取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()方法介绍

功能:返回div坐标;
参数:div对象或div的id(字符串);

返回值:对象,有六个属性:

width:div自身的宽度;
height:div自身的高度;
x:div左上角的坐标x;
y:div左上角的坐标y;
scrollLeft:水平滚动条的位置
scrollTop:竖直滚动条的位置

测试页面:

<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 style="width: 599px;height: 499px;background-color: mediumvioletred;" id="divObj" >
</div>
<br>
<input type="button" value="run" onclick="run();" >
<div id="text22" style="width: 400px;" >
  </div>
</body>
</html>

运行结果:

希望本文所述对大家JavaScript程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn