〇、三种方法的优劣
intersectionObserver本以为是最优解,实现时发现效果并不好。
因为这个API的优先级比较低,每次都要等待页面渲染完成之后才能再次响应,所以在快速滑动的时候会出现抖动。
- 流畅度:CSS >= scroll > intersectionObserver
- 性能:CSS>= intersectionObserver >= scroll
- 兼容性:scroll > intersectionObserver > CSS
一、通过监听全局scroll实现
let reference = document.querySelector(".reference")
let nav = document.querySelector(".nav")
document.addEventListener("scroll",(e)=>{
const distance = reference.getBoundingClientRect().top
console.log(distance);
if (distance<=0){
nav.classList.add('fix')
}else {
nav.classList.remove('fix')
}
})
<div class="box"></div>
<div class="reference">
<div class="nav"></div>
</div>
<div class="box"></div>
*{
padding: 0;
margin: 0;
}
body{
height: 1000px;
}
.reference {
height: 100px;
width: 100%;
background-color: #ff2f45;
}
.nav {
width: 100%;
height: 100px;
background-color: #ff2f45;
}
.box {
width: 100px;
height: 100px;
background-color: blue;
}
.fix {
position: fixed;
top: 0;
}
二、通过 intersectionObserver 实现
let reference = document.querySelector(".reference")
let nav = document.querySelector(".nav")
let util = new IntersectionObserver((entries)=>{
const entry = entries[0];
console.log(entry.isIntersecting);
if (entry.isIntersecting) {
nav.classList.remove('fix')
} else {
nav.classList.add('fix')
}
},{
threshold: [1]
})
util.observe(reference)
<div class="box"></div>
<div class="reference">
<div class="nav"></div>
</div>
<div class="box"></div>
*{
padding: 0;
margin: 0;
}
body{
height: 1000px;
}
.reference {
height: 100px;
width: 100%;
background-color: #ff2f45;
}
.nav {
width: 100%;
height: 100px;
background-color: #ff2f45;
}
.box {
width: 100px;
height: 100px;
background-color: blue;
}
.fix {
position: fixed;
top: 0;
}
三、通过CSS实现
<div class="box"></div>
<div class="reference">
<div class="nav"></div>
</div>
<div class="box"></div>
*{
padding: 0;
margin: 0;
}
body{
height: 1000px;
}
.reference {
position: sticky;
top: 0;
}
.nav {
width: 100%;
height: 100px;
background-color: #ff2f45;
}
.box {
width: 100px;
height: 100px;
background-color: blue;
}