offsetWidth与offset Height、offsetLeft与offsetTop详解
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>offset</title>
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
width: 300px;
height: 300px;
padding: 100px;
margin-left: 100px;
margin-top: 100px;
background: #d00;
position: relative;
}
.box2 {
width: 100px;
height: 100px;
background: #d0d;
position: absolute;
/*left: 100px;*/
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">
<div class="box3"></div>
</div>
</div>
</body>
<script>
var box1 = document.getElementsByClassName('box1')[0];
var box2 = document.getElementsByClassName('box2')[0]
var box3 = document.getElementsByClassName('box3')[0]
//offsetHeight和offsetWidth
/**
* offsetHeight和offsetWidth监测盒子的宽高
* 包括本身、padding、border, 不包括margin
* offsetHeight = width + paddling-top + padding-bottom + border-top + border-bottom
*/
console.log(box1.offsetHeight)
// offsetLeft和offsetTop
/**
* offsetLeft和offsetTop监测距离父盒子有定位的左/上的距离
* 返回上级盒子(有定位的)左边的位置
* 如果先辈没有定位则以body为基准
* offsetLeft从先辈有定位的padding开始计算(border不算)
* offsetLeft = style.left(没有px)
*/
//offsetLeft与style.left区别
/**
* 1.最大区别在于offsetLeft可以返回没有定位盒子的距离左侧的位置(若父辈没有定位,offsetLeft以body为准;style.left则返回空字符串)
* 2.offsetLeft 返回的是数字,style.left返回的是字符串,除了数字以外带有单位px
* 3.offsetLeft 只读,style.left可读写,(只读是获取值,可读写是赋值)
* 4.如果没有给HTML元素指定top样式,则style.left返回空字符串
*/
console.log(box2.offsetLeft)
//offsetParent
/**
* offsetParent 监测父辈盒子中带有定位的的盒子
* 父辈盒子中没有定位,返回body
* 若有返回最近的
*/
console.log(box3.offsetParent)
</script>
</html>