自动滚动至目标区块问题:底部区块25%可见时触发全屏滚动
问题:区块自动滚动触发需求
我遇到一个问题:已花费3小时尝试实现当底部区块的25%进入视野时,自动滚动至该区块并使其占满整个屏幕尺寸。



抱歉,我没有保留这3小时调试的代码,因为所有尝试均无效,已全部删除:(
仅保留以下CSS代码:
section{ min-height: 100vh; display: flex; justify-content: center; align-items: center; } section:nth-child(1){ color: #e0ffff; } section:nth-child(2){ color: #42455a; background: #e0ffff; } section:nth-child(3){ color: #e0ffff; } section:nth-child(4){ color: #42455a; background: #e0ffff; }
解决方案
要实现该效果,核心是监听滚动事件、计算区块可见比例,达到阈值时触发平滑滚动。
完整实现代码
<!DOCTYPE html> <html lang="zh-CN"> <head> <style> section{ min-height: 100vh; display: flex; justify-content: center; align-items: center; margin: 0; padding: 0; } section:nth-child(1){ color: #e0ffff; background: #42455a; } section:nth-child(2){ color: #42455a; background: #e0ffff; } section:nth-child(3){ color: #e0ffff; background: #42455a; } section:nth-child(4){ color: #42455a; background: #e0ffff; } </style> </head> <body> <section>区块1</section> <section>区块2</section> <section>区块3</section> <section>区块4</section> <script> // 节流函数,优化滚动事件性能 function throttle(func, delay) { let lastExec = 0; return function(...args) { const now = Date.now(); if (now - lastExec >= delay) { func.apply(this, args); lastExec = now; } }; } // 检测区块可见度并触发滚动 function handleScroll() { const sections = document.querySelectorAll('section'); const windowHeight = window.innerHeight; sections.forEach(section => { const rect = section.getBoundingClientRect(); const sectionHeight = rect.height; // 计算当前区块的可见高度 const visibleTop = Math.max(rect.top, 0); const visibleBottom = Math.min(rect.bottom, windowHeight); const visibleHeight = visibleBottom - visibleTop; const visibilityRatio = visibleHeight / sectionHeight; // 当可见比例≥25%且未在滚动中时,触发平滑滚动 if (visibilityRatio >= 0.25 && !section.dataset.scrolling) { section.dataset.scrolling = 'true'; window.scrollTo({ top: rect.top + window.scrollY, behavior: 'smooth' }); // 滚动结束后清除标记,避免重复触发 setTimeout(() => { delete section.dataset.scrolling; }, 1000); } }); } // 绑定节流后的滚动事件 window.addEventListener('scroll', throttle(handleScroll, 100)); // 页面加载时初始化检测 window.addEventListener('load', handleScroll); </script> </body> </html>
关键逻辑说明
- 节流函数:控制滚动事件每秒最多触发10次,避免频繁计算导致页面卡顿
- 可见比例计算:通过
getBoundingClientRect()获取区块位置,计算可见高度与总高度的比值 - 滚动触发控制:用
dataset.scrolling标记正在滚动的区块,防止同一区块反复触发滚动 - 平滑滚动:使用
scrollTo的smooth行为实现自然的滚动过渡
内容的提问来源于stack exchange,提问作者Osman H
相关产品推荐
相关产品推荐

