求助:实现页面单次滚动切换一个section的区块滚动效果
实现单次滚动切换单个Section的区块滚动效果
第一步:完善基础CSS样式
先确保每个section占满整个视口,同时禁用页面默认滚动避免冲突:
html, body { height: 100%; margin: 0; padding: 0; overflow: hidden; /* 禁用默认滚动 */ } .container { height: 100%; overflow: hidden; } .sections { height: 100vh; /* 每个区块占满视口高度 */ display: flex; align-items: center; justify-content: center; font-size: 3rem; } /* 可选:添加背景色区分区块 */ #sectionOne { background-color: #f0f9ff; } #sectionTwo { background-color: #e6fffa; } #sectionThree { background-color: #fffbeb; } #sectionFour { background-color: #fef2f2; }
第二步:编写JavaScript逻辑
核心逻辑是通过防抖控制滚动触发频率,根据滚动方向切换到对应区块:
const container = document.querySelector('.container'); const sections = document.querySelectorAll('.sections'); let currentIndex = 0; let isScrolling = false; // 防抖锁,防止连续触发滚动 // 监听滚轮/触控板滚动事件 container.addEventListener('wheel', handleSectionScroll); function handleSectionScroll(e) { // 正在滚动时直接返回,避免连续触发 if (isScrolling) return; // 判断滚动方向:deltaY>0为向下,deltaY<0为向上 const scrollDown = e.deltaY > 0; // 计算目标区块索引 if (scrollDown && currentIndex < sections.length - 1) { currentIndex++; } else if (!scrollDown && currentIndex > 0) { currentIndex--; } else { // 已到边界,不执行滚动 return; } // 标记正在滚动 isScrolling = true; // 平滑滚动到目标区块 container.scrollTo({ top: sections[currentIndex].offsetTop, behavior: 'smooth' }); // 滚动完成后解锁,时长对应平滑动画的大致耗时 setTimeout(() => { isScrolling = false; }, 800); }
关键细节说明
- 防抖锁
isScrolling:解决触控板、苹果鼠标连续触发滚动事件的问题,确保单次滚动只切换一个区块 - 平滑滚动:通过
scrollTo的behavior: 'smooth'实现自然过渡,替代生硬跳转 - 边界控制:滚动到第一个或最后一个区块时,不再执行切换操作
- 兼容性:
wheel事件兼容绝大多数现代浏览器,适配鼠标、触控板等多种输入设备
内容的提问来源于stack exchange,提问作者Haris Khanzada
相关产品推荐
相关产品推荐

