默认禁用页面滚动,点击图标后启用滚动的实现咨询
解决方案:滚动控制实现
需求回顾
- 页面加载完成后默认禁止滚动
- 点击向下图标后,启用滚动并自动滚动到
introduction区块 - 当滚动回仅显示
start顶部区块时,再次禁止滚动,需点击图标恢复
纯CSS局限性说明
纯HTML/CSS无法实现滚动状态动态切换(尤其是滚动回顶部自动禁用),因为CSS没有监听滚动事件的能力,也无法根据滚动位置触发样式变更,因此必须使用JavaScript方案。
修改后的完整代码
HTML代码
</head> <body> <header class="start"> <h1 class="blur-in">Welcome, take your time.</h1><br> <div class="activateScroll"> <a href="#introduction"><i class="fa-solid fa-chevron-down fa-2x slide-in"></i></a> </div> </header> <main> <div id="fixedNavbar"> <nav> <ul> <li><a href="">home</a></li> <li><a href="">skills & work</a></li> <li><a href="">about me</a></li> <li><a href="">contact</a></li> </ul> </nav> </div> <section> <div id="introduction" class="introduction"> <h2>Introduction</h2> <p>这里是introduction区块内容,为了测试滚动,需要足够的高度。</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> <p>更多内容示例...</p> </div> </section> </main> <footer> </footer> <script> // 初始禁用页面滚动 document.body.style.overflow = 'hidden'; // 获取触发元素和目标区块 const activateBtn = document.querySelector('.activateScroll a'); const introduction = document.getElementById('introduction'); // 点击图标时启用滚动并滚动到目标区块 activateBtn.addEventListener('click', function(e) { e.preventDefault(); // 阻止默认锚点跳转 document.body.style.overflow = 'auto'; introduction.scrollIntoView({ behavior: 'smooth' }); }); // 监听滚动事件,回到顶部时禁用滚动 window.addEventListener('scroll', function() { const scrollTop = window.pageYOffset || document.documentElement.scrollTop; if (scrollTop <= 0) { document.body.style.overflow = 'hidden'; } }); </script> </body> </html>
CSS代码
* { padding: 0; margin: 0; box-sizing: border-box; font-family: 'Libre Franklin'; } html, body { width: 100%; scroll-behavior: smooth; } .start { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; background-color: #f5f5f5; } #fixedNavbar { position: sticky; top: 0; width: 100%; background-color: #ffffff; padding: 1rem 0; box-shadow: 0 2px 4px rgba(0,0,0,0.1); z-index: 100; } #fixedNavbar ul { display: flex; list-style: none; gap: 2rem; justify-content: center; } #fixedNavbar a { text-decoration: none; color: #333; font-weight: 500; } .introduction { min-height: 200vh; padding: 2rem; background-color: #e8e8e8; }
关键逻辑说明
- 初始禁用滚动:通过JS设置
body.style.overflow = 'hidden',阻止页面滚动 - 点击触发滚动:监听图标点击事件,启用滚动后用
scrollIntoView实现平滑滚动到目标区块 - 滚动回顶部禁用:监听页面滚动事件,当滚动距离
scrollTop小于等于0时,再次禁用滚动
内容的提问来源于stack exchange,提问作者jschmidt
相关产品推荐
相关产品推荐

