用法:
object.getBoundingClientRect( ) 返回一个对象。
DOMRect 对象包含了一组用于描述边框的只读属性——left、top、right和bottom,单位为像素。
- rect() 返回的 width 和 height 包括元素的边框。 rect ().width=width+border*2 , rect ().height=height+border*2
- 除了 width 和 height 外的属性都是相对于视口的左上角位置而言的。
例子说明
1. 用 document.documentElement 返回网页的根节点(<html>)
2. 执行 object.getBoundingClientRect( ) 会得到元素的 top、right、bottom、left、width、height 属性,这些属性以一个对象的方式返回。
<html>
<head>
<style>
:checked{
color:red}
</style>
</head>
<body>
<button onclick="cli()">
点击
</button>
<script>
function cli(){
var h=document.documentElement
var info=h.getBoundingClientRect()
console.log(h)
console.log(info)
console.log(info.width)
}
</script>
</body>
</html>
body 元素的 rect 盒子
- 查看body元素的rect 盒子发现,body 元素在默认情况下,margin=8px(chrome 浏览器)
var body=document.getElementById("body")
var bodyinfo=body.getBoundingClientRect()
div 元素的 rect 盒子
一、rect 盒子的 width 和height
- rect( ) 返回的width,是元素的宽+左右两边边边框的值: rect().width=width +border*2
- rect( ) 返回的height,是元素的高+上下边框的值: rect().height=height +border*2
<html>
<head>
<style>
html{
background-color:grey;
margin:0 0;
}
div{
position:relative;
color:yellow;
top:0;
left:0;
width:100px;
height:100px;
border:solid 10px
}
</style>
</head>
<body id="body">
<div id="div">一个元素</div>
<button onclick="cli()">
点击
</button>
<script>
function cli(){
var div=document.getElementById("div")
var divinfo=div.getBoundingClientRect()
console.log(divinfo)
}
</script>
</body>
</html>
二、x,y 坐标:元素左上角起始点相对于浏览器视窗的位置
- 网页发生上下滚动,rect() 的 y 坐标发生变化;
- 发生左右滚动,x 坐标变化