getBoundingClientRect()获取元素相对浏览器视窗的坐标值

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <style>
        body{height:1000px; margin:0; padding:0; border:5px solid green; background:#999;}
        #tdiv{position:absolute; top:100px; left:300px; background:#eee; width:500px; height:300px;}
    </style>
    <script>
    function $(id){return document.getElementById(id);}
    window.onload=init;
    function init(){
        $('tdiv').onclick=function(){
            if(document.documentElement.getBoundingClientRect){ //若浏览器支持 getBoundingClientRect方法
                alert('元素左边到浏览器视窗左上角的距离left:'+this.getBoundingClientRect().left+'\n'+'元素右边到浏览器视窗左上角的距离right:'+this.getBoundingClientRect().right+'\n 元素上边到浏览器视窗左上角的距离top:'+this.getBoundingClientRect().top+'\n 元素下边到浏览器视窗左上角的距离bottom:'+this.getBoundingClientRect().bottom)
                //getBoundingClientRect() 获得元素相对于浏览器窗口以左上角为原点的坐标系统的 坐标值
                // 当文档内容向左滚动或向右滚动时 相对坐标值可能会为负数
            }
        }

    }
    </script>
</head>
<body>
    <div id="tdiv">i am a div tag <br />top:100px; left:300px; background:#eee; width:500px; height:300px;</div>
</body>
</html>

 

posted @ 2013-04-04 12:46  stephenykk  阅读(692)  评论(0编辑  收藏  举报