* 获取元素偏移量(要求会背,因为后续会有项目,需要使用)
* 获取元素在页面上相对参考父级的左边和上边的距离
*
* 参考父级:
* 其实就是假设你要给一个元素'绝对定位',他是根据谁来进行定位,那么这个元素的偏移量参考父级就是谁
<div class="box1"><div class="box2"></div></div>
* {
margin: 0;
padding: 0;
}
.box1 {
width: 400px;
height: 400px;
background-color: pink;
position: relative;
left: 20px;
top: 20px;
}
.box2 {
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
left: 100px;
top: 200px;
}
// 0.获取元素
var box2 = document.querySelector('.box2')
- !1. 元素.offsetParent 获取元素的相对父级
// 1.元素.offsetParent 获取元素的相对父级
console.log(box2.offsetParent)
- !2. 元素.offsetLef 获取元素距离左边的距离
// 2. 元素.offsetLef 获取元素距离左边的距离
console.log('offsetLef:', box2.offsetLeft)
- !3. 元素.offsetTOP 获取元素距离顶部的距离
// 3. 元素.offsetTOP 获取元素距离顶部的距离
console.log('offsetTop:', box2.offsetTop)