<!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">
<style>
body {
margin: 0;
}
div {
background-color: chartreuse;
width: 100px;
height: 100px;
}
#obj1 {
margin-top: 20px;
}
#obj2 {
margin-top: 500px;
margin-left: 500px;
}
</style>
<title>getBoundingClientRect()</title>
</head>
<body>
<div id="obj1">
我是居顶部的div元素
</div>
<div id="obj2">
我是一个包含margin-top的div元素
</div>
</body>
<script>
const obj1Postion = obj1.getBoundingClientRect();
console.log(obj1Postion);
/*
{
"x": 0,
"y": 20,
// 元素自身的宽
"width": 100,
// 元素自身的高
"height": 100,
// 元素上边到视窗上边的距离
"top": 20,
// 元素右边到视窗左边的距离
"right": 100,
// 元素下边到视窗上边的距离
"bottom": 120,
// 元素左边到视窗左边的距离
"left": 0
}
*/
console.log('------------------------------')
const obj2Postion = obj2.getBoundingClientRect();
console.log(obj2Postion);
/*
{
"x": 500,
"y": 620,
"width": 100,
"height": 100,
此处的top之所以是620,是因为 top = margin-top的500px + obj1元素自身的高度100px + obj1元素的margin-top的20px
"top": 620,
"right": 600,
"bottom": 720,
"left": 500
}
*/
window.addEventListener('scroll', function() {
const rectObject1 = obj1.getBoundingClientRect();
console.log(rectObject1);
console.log('rectObject1的top值为:', rectObject1.top);
// 当滚动条进行滚动,id为obj1的元素即将消失在视图中时,可以设置该元素为固定定位,一直停留在页面上
if (rectObject1.top < 0) {
obj1.style.position = 'fixed'
obj1.style.top = 0;
obj1.style.marginTop = 0;
}
console.log('------监听分割线------')
const rectObject2 = obj2.getBoundingClientRect();
console.log(rectObject2);
console.log('