offsetTop为需要吸顶元素距离顶部的高度
scrollTop为当前滚动条距离顶部的高度
当scrollTop 大于 offsetTop 这时就改变吸顶元素的class
代码:
let offsetTop = document.querySelector('.search').offsetTop;
window.addEventListener("scroll",(e)=>{
let scrollTop = e.target.scrollingElement.scrollTop
console.log(offsetTop,scrollTop)
if (scrollTop > offsetTop) {
document.querySelector('.search').className="search sticky";
} else {
document.querySelector('.search').className="search";
}
})
.sticky{
position: fixed;
left: 0;
right: 0;
top: 0;
z-index: 980;
}