想实现吸顶的效果,搜索后发现可以使用getBoundingClientRect来实现。但我测试的时候发现当元素到达吸顶的条件后,继续往下滚动,吸顶元素会在static和fixed之间来回切换导致元素一直在闪烁。打印top值会发现一会是正常的top值,一会是0,想请问下是为什么?
以下是代码
<style>
p {
margin: 0;
height: 47px;
}
.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 9;
}
</style>
</head>
<body>
<div style="background-color: red; height: 200px;">12312321</div>
<div style="height: 47px">
<p id="p">吸顶</p>
</div>
<div style="background-color: yellow; height: 2000px;">12312321</div>
<script>
window.addEventListener('scroll', function () {
const p = document.querySelector('#p');
const top = p.getBoundingClientRect().top;
console.log(top)
if (top < 0) {
p.classList.add('fixed');
} else {
p.classList.remove('fixed');
}
})
</script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…