> 利用 window对象的pageYOffset属性
<script>
window.addEventListener("scroll",handleScroll,true);
let header = document.getElementById("header");
let prePosition = 0;
let preStatus = -1; //0向下,1向上 为了增加缓冲
function handleScroll(e){
let newYPosi = window.pageYOffset;
let currentStatus = newYPosi - prePosition;
prePosition = newYPosi;
//向下
if(currentStatus > 0){
if(preStatus === 0){
return;
}else{
preStatus = 0;
}
header.style.position=""
console.log("向下滚动!!",newYPosi,prePosition);
} else{
if(preStatus === 1){
return;
}else{
preStatus = 1;
}
header.style.position="sticky";
header.style.top="1em";
console.log("向上!!",newYPosi,prePosition);
}
}
</script>