getBoundingClientRect() 来获取页面元素的位置

一、样式:

<style>
body,div{ margin:0; padding:0}
.div-info{ width:200px; height:200px;border:1px solid #ccc; background:#f2f2f2; font:normal 12px/22px SimSun; position:absolute;top:200px; left:200px}
</style>

 二、js

<script type="text/javascript">
function divPos(){
var obj = document.getElementById('demo');
alert("left:"+obj.getBoundingClientRect().left)
alert("top:"+obj.getBoundingClientRect().top)
alert("right:"+obj.getBoundingClientRect().right)
alert("bottom:"+obj.getBoundingClientRect().bottom)
var X= obj.getBoundingClientRect().left+document.documentElement.scrollLeft;
var Y = obj.getBoundingClientRect().top+document.documentElement.scrollTop;
alert("Demo的位置是X:"+X+";Y:"+Y)
}
</script> 

 三、html

<body style="width:100%; height:100%;">
      <div id="demo"  class="div-info" onclick="divPos()">div在浏览器窗口中的位置是,居上200px,居左200px。</div>
</body>

 四、图示(top/left/right/bottom具体指示)

posted @ 2014-04-28 19:27  San's养乐多大人  阅读(275)  评论(0编辑  收藏  举报