如何实现用户滚动100vh时切换文本内容且不跳转至下一节?
实现滚动触发文本切换并锁定滚动的方案
核心思路
- 第一个文本区块占满一屏(100vh),内部包含两个需要切换的文本元素,通过CSS过渡实现淡入淡出+位移动画。
- 监听滚动事件,当滚动距离接近一屏(留出小阈值避免误触)时,触发文本切换动画,同时锁定滚动位置在一屏高度,防止用户提前滚动到下一个区块。
- 动画完成后,解除滚动锁定,允许用户继续滚动到下一个区块。
完整实现代码
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>滚动文本切换动画</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { overflow-y: scroll; scroll-behavior: smooth; } .text-section { height: 100vh; display: flex; align-items: center; justify-content: center; position: relative; background: #f0f0f0; } .text-item { font-size: 3rem; font-weight: bold; position: absolute; opacity: 0; transition: opacity 0.8s ease, transform 0.8s ease; } .text-item.active { opacity: 1; transform: translateY(0); } .text-item.first { opacity: 1; transform: translateY(0); } .text-item.second { transform: translateY(20px); } .next-section { height: 100vh; display: flex; align-items: center; justify-content: center; background: #333; color: white; font-size: 2rem; } </style> </head> <body> <section class="text-section"> <div class="text-item first">初始文本内容</div> <div class="text-item second">切换后的文本内容</div> </section> <section class="next-section">下一个区块内容</section> <script> const textSection = document.querySelector('.text-section'); const firstText = document.querySelector('.text-item.first'); const secondText = document.querySelector('.text-item.second'); let hasSwitched = false; let isAnimating = false; window.addEventListener('scroll', () => { const scrollTop = window.pageYOffset || document.documentElement.scrollTop; const viewportHeight = window.innerHeight; // 当滚动到接近一屏高度,且未触发过切换、不在动画中时执行 if (scrollTop >= viewportHeight - 20 && !hasSwitched && !isAnimating) { isAnimating = true; // 锁定滚动位置在一屏处 window.scrollTo(0, viewportHeight); // 执行文本切换动画:先隐藏初始文本,再显示切换后的文本 firstText.classList.remove('active'); setTimeout(() => { secondText.classList.add('active'); }, 400); // 动画完成后解除锁定,标记已完成切换 setTimeout(() => { hasSwitched = true; isAnimating = false; }, 1200); } }); </script> </body> </html>
自定义调整说明
- 修改
.text-item的font-size、transition参数,可以调整文本大小和动画快慢。 - 调整滚动触发阈值(
viewportHeight - 20中的20),能改变触发切换的滚动位置。 - 直接替换文本内容、区块背景色,就能适配你的具体需求。
内容的提问来源于stack exchange,提问作者Aakash Mishra
相关产品推荐
相关产品推荐

