日期:2014-05-16  浏览次数:20496 次

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>