天天看点

js获取div的坐标

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

如何方法可以实现.

js获取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  

js获取div的坐标

com.whuang.hsj.divcoordinate()方法介绍

功能:返回div坐标;

参数:div对象或div的id(字符串);

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

width:div自身的宽度;

height:div自身的高度;

x:div左上角的坐标x;

y:div左上角的坐标y;

scrollleft:水平滚动条的位置

scrolltop:竖直滚动条的位置

测试页面:

js获取div的坐标

<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>  

 运行结果:

js获取div的坐标

参考:

http://hw1287789687.iteye.com/admin/blogs/2156296

http://hw1287789687.iteye.com/admin/blogs/2155772

继续阅读