标签:obj1 console log getBoundingClientRect 元素 使用 margin top
<!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('
标签:obj1,console,log,getBoundingClientRect,元素,使用,margin,top
来源: https://blog.csdn.net/feyehong/article/details/123145510
本站声明:
1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。