滚动从section1跳转至section2时短暂触发CSS动画的实现方法
问题解答
这个需求完全可以实现,不需要修改你编写的动画核心关键帧规则,仅需补充少量CSS控制类和几行原生JavaScript逻辑,就能满足所有要求。
实现逻辑
- 保留原有核心代码不动:包括两个区块的锚点结构、基础平滑滚动配置、
example关键帧定义的全部动画效果,这些核心内容一行都不需要修改 - 把原本直接绑定在动画元素上的无限循环动画属性,拆分到独立的触发类中:默认状态下动画不会启动,只有给元素加上触发类时动画才会运行
- 拦截Section1到Section2的锚点默认点击行为,避免点击后直接跳转到目标区块
- 点击锚点时先给动画元素添加触发类启动动画,等动画完整跑完设定的4秒时长后,再通过JS控制页面平滑滚动到Section2位置,同时移除动画触发类,让动画自动停止,不会无限循环
完整可运行代码
<!DOCTYPE html> <html> <head> <style> html { scroll-behavior: smooth; } #section1 { height: 100vh; } #section2 { height: 100vh; } /* 动画元素基础样式 */ .animation-box { width: 100px; height: 100px; background-color: red; position: relative; } /* 动画触发类,仅控制动画的启动和运行次数,不改动动画核心效果 */ .animation-box.active { animation-name: example; animation-duration: 4s; animation-iteration-count: 1; } /* 原有动画核心关键帧完全保留,未做任何修改 */ @keyframes example { 0% {background-color:red; left:0px; top:0px;} 25% {background-color:yellow; left:200px; top:0px;} 50% {background-color:blue; left:200px; top:200px;} 75% {background-color:green; left:0px; top:200px;} 100% {background-color:red; left:0px; top:0px;} } </style> </head> <body> <div class="main" id="section1"> <h2>Section 1</h2> <a href="#section2" id="jumpBtn">Click to go Section 2 </a> <div class="animation-box"></div> </div> <div class="main" id="section2"> <h2>Section 2</h2> </div> <script> const jumpBtn = document.getElementById('jumpBtn'); const animationBox = document.querySelector('.animation-box'); const section2 = document.getElementById('section2'); // 时长和CSS中animation-duration保持一致即可 const ANIMATION_RUN_TIME = 4000; jumpBtn.addEventListener('click', (e) => { // 阻止锚点默认跳转行为 e.preventDefault(); // 添加类触发动画 animationBox.classList.add('active'); // 等待动画运行结束后,平滑滚动到目标区块 setTimeout(() => { section2.scrollIntoView({ behavior: 'smooth' }); // 滚动完成后移除类,重置动画状态 setTimeout(() => { animationBox.classList.remove('active'); }, 600) }, ANIMATION_RUN_TIME) }) </script> </body> </html>
调整说明
- 代码里仅调整了动画的触发逻辑和循环次数参数,你原先写的动画运动轨迹、颜色变化、运行时长等核心效果完全没有改动
- 如果需要修改动画运行时长,只需要同步修改CSS里的
animation-duration属性值和JS里的ANIMATION_RUN_TIME变量值即可,其他逻辑不需要变动 - 动画只会在点击跳转按钮时触发一次,运行完4秒后自动停止,不会出现无限循环的情况,同时页面会平滑滚动到Section2位置,完全匹配你的需求
内容的提问来源于stack exchange,提问作者User
相关产品推荐
相关产品推荐

