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>

 

转载于:https://www.cnblogs.com/stephenykk/archive/2013/04/04/2999253.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值