1.offsetParent:获取第一个定位的父元素,如果所有父元素都没有定位,则返回body:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>location</title>
<style>
.content {
height: 500px;
width: 500px;
margin: 0 auto;
background-color: pink;
}
.father {
height: 400px;
width: 400px;
background-color: #ccc;
}
.son {
height: 300px;
width: 300px;
background-color: #000;
}
</style>
<script>
window.addEventListener('load', function() {
let sonDiv = document.querySelector('.son');
console.log(sonDiv.offsetParent);
});
</script>
</head>
<body>
<div class="content">
<div class="father">
<div class="son"></div>
</div>
</div>
</body>
</html>
给content加上定位:
.content {
position: relative;
height: 500px;
width: 500px;
margin: 0 auto;
background-color: pink;
}
这时获取到的offsetParent是content盒子.
2.offsetTop、offsetLeft:距离offsetParent上边框、左边框的内侧的距离(不包含边框的宽度):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>location</title>
<style>
.content {
position: relative;
padding-top: 50px;
border-top: 10px solid #ccc;
height: 500px;
width: 500px;
margin: 0 auto;
background-color: pink;
overflow: hidden;
}
.father {
margin: 50px;
height: 400px;
width: 400px;
background-color: #ccc;
overflow: hidden;
}
.son {
border-top: 10px solid red;
margin: 50px;
height: 300px;
width: 300px;
background-color: #000;
}
</style>
<script>
window.addEventListener('load', function() {
let sonDiv = document.querySelector('.son');
console.log('offsetTop: ' + sonDiv.offsetTop);
console.log('offsetLeft: ' + sonDiv.offsetLeft);
});
</script>
</head>
<body>
<div class="content">
<div class="father">
<div class="son"></div>
</div>
</div>
</body>
</html>
这里的content为相对定位,有:(1)10px的上边框,(2)50px的上内边距,(3)father盒子有50px的外边距,(4)son盒子有50px的外边距,(5)10px的上边框,可以计算出offsetTop:(2) + (3) + (4) = 150px,offetLeft:(3) + (4) = 100px.
3.offsetHeight、offsetWidth:元素高度和宽度,包括边框、内边距、内容:
window.addEventListener('load', function() {
let sonDiv = document.querySelector('.son');
console.log('offsetHeight: ' + sonDiv.offsetHeight);
console.log('offsetWidth: ' + sonDiv.offsetWidth);
});
这里offsetHeight为10px的上边框+width(300px) = 310px,offsetWidth为width:300px;