【javascript基础】之【确定元素坐标】


【javascript基础】之【确定元素坐标】

  IE、FireFox3以及更高版本和Opera9.5以及更高版本都提供了getBoundingClientRect()方法,这个方法返回一个矩形对象,left、top、right、bottom,这些属性返回的是节点相对于浏览器(0,0)坐标(节点相对于视口的位置)的位置。但IE认为文档的左上角坐标是(2,2),而FireFox Opera则将传统的(0,0)作为起点坐标,因此开始的时候,检查一下位于(0,0)的位置。

 demo:

<div id="msg" style="width:400px;height:400px;background:#0046a3;margin:40px;"></div>
<script type="text/javascript">

var m = document.getElementById("msg");

function offset(elem){
     if(!elem){
         throw '不是一个有效的节点';
    }
     var scrollTop = document.documentElement.scrollTop,
        scrollLeft = document.documentElement.scrollLeft,
        returnValue =  null;
     if(elem.getBoundingClientRect){    // 支持getBoundingClientRect
         if( typeof arguments.callee.offset !== 'number'){
             var temp = document.createElement("div");
            temp.style.cssText = "position:absolute;top:0;left:0;";
            document.body.appendChild(temp);
            arguments.callee.offset = - temp.getBoundingClientRect().top - scrollTop;    // 为了防止函数调用的时候,窗口被滚动了
            document.body.removeChild(temp);
            temp =  null;
        }
         var rect = elem.getBoundingClientRect(),
            offset = arguments.callee.offset;
        returnValue = {
            left : rect.left + offset,
            right : rect.right + offset,
            top : rect.top + offset,
            bottom : rect.bottom + offset
        };
    } else{                          // 不支持getBoundingClientRect
         var offsetParent = elem, 
            left = 0,
            top = 0;
         while( offsetParent !=  null ){
            left += offsetParent.offsetLeft;
            top += offsetParent.offsetTop;
            offsetParent = elem.offsetParent;
        }
        returnValue = {
            left : left - scrollLeft,
            right : left + elem.offsetWidth - offsetLeft,
            top : top - scrollTop,
            bottom : top + elem.offsetHeight - scrollTop
        };
    }
    
     return returnValue;
}

var t = offset(m);
alert('top:' + t.top + '\n' + 'left:' + t.left + '\n' + 'right:' + t.right + '\n' + 'bottom:' + t.bottom);

</script>

 参考:javascript高级程序设计第二版


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM