一、前言
元素大小平时在开发中或多或少都有用到,时常在各种属性中犹豫不决,不知道该用哪个,现在来对偏移量(offsetTop),客户区大小(clientTop),滚动大小(scrollTop)和确定元素大小(getBoundingClientRect().top)做个总结。
二、分析
offsetTop:元素的上外边框至包含元素的上内边框之间的像素距离。这句话主要的点在于包含元素,包含元素的引用保存在offsetParent中,offsetParent不等同于parentNode,例如,td元素的offsetParent是table元素。平时我们将某个元素的position设为relactive,那么他的子元素的offsetParent就是该元素,offsetTop则为该元素的上外边框到offsetParent元素的下内边框的距离,如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body {
margin: 0;
padding: 0;
}
.inside-bor {
position: relative;
box-sizing: content-box;
border: 10px solid #cccccc;
width: 100px;
height: 100px;
}
.outer-bor {
box-sizing: content-box;
border: 10px solid goldenrod;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div style="width: 100px;height: 100px;background-color: chartreuse"></div>
<div class='inside-bor' id="parent">
<div>
<div id="children" class="outer-bor">我我我</div>
</div>
</div>
<script>
console.log(document.getElementById('children').offsetTop);
console.log(document.getElementById('children').offsetParent);
</script>
</body>
</html>
offsetHeihgt:包含边框,内边距和内容的高度。
clientHeight:内容加内边框的高度。
scrollTop:被隐藏在内容区域上方的像素。
scrollHeight:在没有滚动条的情况下,元素内容的总高度。
getBoundingClientRect():有4个属性,top,left,right,bottom。都是相对于浏览器视口的像素。