offset家族介绍
offset这个单词本身是–偏移,补偿,位移的意思。
js中有一套方便的获取元素尺寸的办法就是offset家族;
offsetWidth、offsetHight 、offsetLeft、offsetTop以及offsetParent
共同组成了offset家族。
offset属性家族:offsetWidth offsetHeight offsetLeft offsetTop
offset属性家族(offsetWidth offsetHeight)获取元素的宽高的特点:
1.可以获取行内属性 也可以获取行外属性
2.获取的属性值是nummber类型 而且不带单位
3.获取到的是页面显示的元素的真实宽高(width/height + padding + border)
offsetWidth和offsetHight (检测盒子自身宽高+padding+border)
这两个属性,他们绑定在了所有的节点元素上。获取之后,只要调用这两个属性,我们就能够获取元素节点的宽和高。
offset宽/高 = 盒子自身的宽/高 + padding +border;
offsetWidth = width+padding+border;
offsetHeight = Height+padding+border;
offsetParent (检测父系盒子中带有定位的父盒子节点)
offsetParent:获取元素最近的父级定位元素,返回该对象的父级 (带有定位)
1.如果元素自身是固定定位,那么获取到的父级为null
2.如果元素自身不是固定定位(absolute relative) 那么就往上找父级定位,如果所有的父级元素
都没有定位,那么找到的定位父级就是body。
3.body的定位父级为null
因为偏移量家族的Element的属性,所以每一个元素都具有offsetParent这个属性,它用来获取自己的祖先元素中,并且是已经定位的祖先元素,还有优先获取距离自己最近的元素,如果没有定位的祖先元素了,就是以body为其参考,获取body的标签。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
#box{
width: 100px;
height: 100px;
background-color: #0f0;
/* position:absolute; */
}
.two{
width: 200px;
height: 200px;
background-color: pink;
/* position: relative; */
}
.three{
width: 300px;
height: 300px;
background-color: skyblue;
/* position:absolute; */
}
</style>
</head>
<body>
<div class="three">
<div class="two">
<div id="box"></div>
</div>
</div>
</body>
<script type="text/javascript">
var box=document.getElementById("box");
console.log(box.offsetParent);
console.log(document.body.offsetParent); //null
</script>
</html>
offsetLeft和offsetTop (检测距离父盒子有定位的左/上面的距离)
offsetTop offsetLeft:获取元素在页面上的真实位置
offsetTop:获取到的是元素上外边框到定位父级(offsetParent)上内边框的距离
offsetLeft:获取到的是元素左外边框到定位父级(offsetParent)左内边框的距离
offsetLeft和style.left区别
1、最大区别在于offsetLeft可以返回没有定位盒子的距离左侧的位置。而 style.left不可以
2、offsetTop 返回的是数字,而 style.top 返回的是字符串,除了数字外还带有单位:px。
3、offsetTop 只读,而 style.top 可读写。(只读是获取值,可写是赋值)
4、如果没有给 HTML 元素指定过 top 样式,则style.top 返回的是空字符串。
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.one{
width: 100px;
height: 100px;
background-color: skyblue;
border: 10px pink solid;
margin: 20px;
position: absolute;
top: 50px;
left: 50px;
}
.two{
width: 200px;
height: 200px;
background-color: #00FF00;
border: 10px solid purple;
position: relative;
}
</style>
</head>
<body>
<div class="two">
<div id="box" class="one"></div>
</div>
</body>
<script type="text/javascript">
var box=document.getElementById("box");
console.log(box.offsetTop);
console.log(box.offsetLeft);
</script>
</html>