当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


HTML DOM getBoundingClientRect()用法及代码示例


HTML DOM getBoundingClientRect()方法将相对位置返回到视口。
它返回八个属性:左,上,右,下,x,y,宽度,高度。
滚动将更改位置值。

用法:

var rect = div.getBoundingClientRect();

例:


<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        HTML | DOM getBoundingClientRect() Method 
    </title> 
    <script> 
        function myFunction() { 
            var div = document.getElementById("myDiv"); 
            var rectangle = div.getBoundingClientRect(); 
            x = rectangle.left; 
            y = rectangle.top; 
            w = rectangle.width; 
            h = rectangle.height; 
  
            alert("Left:" + x + ", Top:" + y + 
                ", Width:" + w + ", Height:" + h); 
        } 
    </script> 
</head> 
  
<body> 
    <button onclick="myFunction()"> 
        GET POSITION 
    </button> 
    <div style="height:300px;  
                width:400px; 
                overflow:auto;"> 
  
        <div id="myDiv" style="width:350px; 
                               height:250px;  
                               background-color:lightgreen; 
                               border:2px SOLID green;"> 
  
            Use scrollbar to change the position. 
        </div> 
        <div style="width:1500px; 
                    height:1500px; "> 
        </div> 
    </div> 
    <br> 
  
</body> 
  
</html>

输出:
点击前:

点击后:

支持的浏览器:

  • Chrome 1.0
  • Internet Explorer 9.0
  • 火狐3.0
  • Opera 9.5
  • Safari 4.0


相关用法


注:本文由纯净天空筛选整理自AkshayGulati大神的英文原创作品 HTML | DOM getBoundingClientRect() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。