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

解决方案 »

  1.   


    offsetTop是相对于上一层的父容器的位置吧?我要的是相对于整个页面的坐标啊?
      

  2.   


    <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>看看这个例子。。