请看下面的代码和输出的结果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html {
height: 2000px;
}
.ye {
position: relative;
/* margin: 100px; */
width: 600px;
height: 600px;
background-color: pink;
}
.father {
/* position: relative; */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 400px;
height: 400px;
background-color: gray;
}
.son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="ye">
<div class="father">
<div class="son"></div>
</div>
</div>
<script>
const ye = document.querySelector('.ye')
const father = document.querySelector('.father')
const son = document.querySelector('.son')
// 需求1 拿到son盒子具体页面顶部和左部的距离
// // 思路 son盒子距离father盒子的距离 x1 father盒子距离ye盒子的距离x2 x1+x2
let sonTop = son.offsetTop
console.log(sonTop, '这是sonTop')//200
let fatherTop = father.offsetTop
console.log(fatherTop,'这是fatherTop') //300
</script>
</body>
</html>
结果:
为什么会是这个结果呢?按道理不应该都是100吗?offsetTop 是基于自己有定位的父盒子的上距离 为什么这里会得到的结果是200 和300呢?请接着往下看
请看以下圈起来的代码
不难得知 我们实现居中是用的定位+transform 去实现的。
再次强调offsetTop 是基于自己有定位的父盒子的上距离。之和定位打交道,所以我们只能看top和left之后的位置,至于后面用了transform 进行了位移,offsetTop是不管的,所像这样的情况offsetTop是不能准确获取到我们想要的值的
请看js修改后的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html {
height: 2000px;
}
.ye {
position: relative;
/* margin: 100px; */
width: 600px;
height: 600px;
background-color: pink;
}
.father {
/* position: relative; */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 400px;
height: 400px;
background-color: gray;
}
.son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="ye">
<div class="father">
<div class="son"></div>
</div>
</div>
<script>
const ye = document.querySelector('.ye')
const father = document.querySelector('.father')
const son = document.querySelector('.son')
const sonInfo = son.getBoundingClientRect()
console.log(sonInfo.top, '距离顶部的距离')
const n = document.documentElement.scrollTop
console.log(n, '页面滚动的距离')
const sonTop = sonInfo.top + n
console.log(sonTop, '这是son盒子距离顶部的距离')
</script>
</body>
</html>
结果:
图1:
图2:
所以像这样的情况,推荐使用 getBoundingClientRect() 方法,这样我们可以拿到距离可视区域顶部的值,因为他是会改变的,我们只需要加上滚动的距离就可以的到盒子距离顶部准确的距离了
以上解释的是offsetTop,offsetLeft也是同理。如有误导还请指出,谢谢