getBoundingClientRect 函数

之前没有听说过这个函数,于是查了相关资料,该函数获取元素在当前页面的位置,返回结果为一个ClientRect对象。

这个对象有top、bottom、left、right几个属性。

top:元素顶部距离页面顶部的大小。

bottom:元素底部距离页面顶部的大小。

left:元素左部距离页面左部的大小。

right:元素右部距离页面左部的大小

举例

代码

<p id="box" style="margin:10px 0 0 50px; 100px; height:30px; background:#ccc;"> </p>
<script type="text/javascript">
  var ob=document.getElementById("box").getBoundingClientRect();  
  alert("上:"+ob.top+"下:"+ob.bottom+"左:"+ob.left+"右:"+ob.right);
</script>

运行结果

代码

<p id="box" style="margin:10px 0 0 50px; 100px; height:30px; background:#ccc;"> </p>
<P id="two" style="500px;height:200px;text-align:center">请点击这里</p>
<script type="text/javascript"> 
  document.getElementById("two").onclick=function(){
     ob=document.getElementById("box").getBoundingClientRect();
     alert("上:"+ob.top+"下:"+ob.bottom+"左:"+ob.left+"右:"+ob.right);
   };
</script>

 运行结果

备注

getBoundingClientRect().left+document.documentElement.scrollLeft 得到元素位于页面的X坐标
getBoundingClientRect().top+document.documentElement.scrollTop 得到元素位于页面的Y坐标

原文地址:https://www.cnblogs.com/blackwood/p/2650995.html