读书人

js或jquery怎样获取htm中div控件相对于

发布时间: 2012-02-23 22:01:35 作者: rapoo

js或jquery怎样获取htm中div控件相对于页面的left和top值
起初我直接通过div.style.top来获取,但是这个div的style中并没有设置过top值,并且是相对位置,所以获取的值为空。 我要得到它相对于整个页面的坐标,怎样可行呢?

[解决办法]

JScript code
<div id="test" style="position:absolute; left:100px; top:200px;">123</div><script>/**     * 坐标     * @param x     * @param y     * @return     */    function CPos(x, y)    {        this.x = x;        this.y = y;    }    /**     * 得到对象的相对浏览器的坐标     * @param ATarget     * @return     */    function GetObjPos(ATarget)    {        var target = ATarget;        var pos = new CPos(target.offsetLeft, target.offsetTop);                var target = target.offsetParent;        while (target)        {            pos.x += target.offsetLeft;            pos.y += target.offsetTop;                        target = target.offsetParent        }        return pos;    }        var obj =  document.getElementById('test')    alert(GetObjPos(obj)['y']) //y坐标    alert(GetObjPos(obj)['x']) //x坐标    </script> 

读书人网 >JavaScript

热点推荐