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 2.0及以上版本
- Edge12及以上
- Internet Explorer 4.0及以上版本
- 火狐3.0及以上版本
- Opera 9.5及以上版本
- Safari 4.0及以上版本