最近在做模掘金论坛的项目,遇到这个问题思考了许久,将此代码记录在这以便于日后回看
//获取滚动条滚动距离
const getScrollTop = () => {
let scrollTop =
document.documentElement.scrollTop ||
window.pageYOffset ||
document.body.scrollTop;
return scrollTop;
}
const initScroll = () => {
let initScrollTop = getScrollTop()//这里拿到了scrollTop是进入页面时最开始的
let scrollType = 0;
window.addEventListener("scroll", () => {
// 重新赋值,因为会改变
let currentScrollTop = getScrollTop();
if (currentScrollTop > initScrollTop) {
// 往下移动
scrollType = 1;
} else {
// 往上移动
scrollType = 0;
}
initScrollTop = currentScrollTop;
// console.log(scrollType);
if (scrollType == 1 && currentScrollTop > 100) {
showHeader.value = false;
} else {
showHeader.value = true;
}
});
onMounted(() => {
initScroll();
})
}