页面头部需上滑两次才显示的功能实现问题求助
问题解决:向上滚动两次及以上才显示页面头部
问题背景
当前页面头部向下滚动时隐藏,向上滚动一次就显示。需求改为仅当向上滚动两次及以上时才显示头部,尝试修改scrollUp_Count > 12这类条件后未达到预期效果,原代码如下:
原JavaScript代码
const body = document.body let lastScroll = 0; let scrollUp_Count = 0; window.addEventListener('scroll', () => { const currentScroll = window.pageYOffset //top of the page if (currentScroll <= 0 ) { body.classList.remove("scroll-up") scrollUp_Count = 0 } // Scrolling down if (currentScroll > lastScroll && !body.classList.contains("scroll-down")) { body.classList.remove("scroll-up") body.classList.add("scroll-down") scrollUp_Count = 0 } // Scrolling up if (currentScroll < lastScroll && body.classList.contains("scroll-down")) { body.classList.remove("scroll-down") scrollUp_Count++ // body.classList.add("scroll-up") if (scrollUp_Count >= 2) { body.classList.add("scroll-up") }} lastScroll = currentScroll })
原CSS代码
.scroll-down header { transform: translate3d(0, -100%, 0 ) } .scroll-up header { filter: drop-shadow(0 -10px 20px rgb(170, 170, 170)) }
问题分析
原代码的scrollUp_Count++会在每一次向上滚动的scroll事件触发时累加(哪怕只是滚动1px),这导致计数的是滚动帧的次数,而非用户的“向上滚动动作次数”。比如用户一次连续向上滚动,会触发几十次scroll事件,计数直接远超2,完全不符合需求。
我们需要的是:从向下滚动切换到向上滚动时,才算一次向上滚动动作,连续的向上滚动过程只算一次,只有当用户完成“向下→向上→向下→向上”这样两次切换时,才满足显示条件。
修改后的代码
调整后的JavaScript代码
const body = document.body let lastScroll = 0; let scrollUpCount = 0; let wasScrollingDown = false; // 记录上一次的滚动方向是否为向下 window.addEventListener('scroll', () => { const currentScroll = window.pageYOffset; // 回到页面顶部时重置所有状态 if (currentScroll <= 0) { body.classList.remove("scroll-up", "scroll-down"); scrollUpCount = 0; wasScrollingDown = false; lastScroll = currentScroll; return; } const isScrollingDown = currentScroll > lastScroll; const isScrollingUp = currentScroll < lastScroll; // 向下滚动时:隐藏头部,仅在从向上切换到向下时累加向上动作计数 if (isScrollingDown) { if (!body.classList.contains("scroll-down")) { body.classList.remove("scroll-up"); body.classList.add("scroll-down"); // 从向上切换到向下,说明完成了一次完整的向上滚动动作 if (!wasScrollingDown) { scrollUpCount++; } } wasScrollingDown = true; } // 向上滚动时:满足两次及以上向上动作则显示头部 else if (isScrollingUp) { wasScrollingDown = false; if (scrollUpCount >= 2) { body.classList.remove("scroll-down"); body.classList.add("scroll-up"); } } lastScroll = currentScroll; });
CSS代码保持不变
.scroll-down header { transform: translate3d(0, -100%, 0); } .scroll-up header { filter: drop-shadow(0 -10px 20px rgb(170, 170, 170)); }
逻辑说明
- 新增
wasScrollingDown变量跟踪滚动方向,只有当从向上滚动切换到向下滚动时,才累加scrollUpCount,代表完成一次完整的向上滚动动作。 - 当用户完成两次及以上的向上滚动动作(即至少经历两次“向下→向上”的切换),向上滚动时才会显示头部。
- 回到页面顶部时重置所有状态,避免计数混乱。
内容的提问来源于stack exchange,提问作者SINAN MOHAMMED
相关产品推荐
相关产品推荐

