如何点击时停止CSS动画并将其还原至第一帧?
如何停止CSS动画并立即回到初始帧?
我的CSS代码如下:
#turbo_fire { transform-box: fill-box; position: absolute; animation-name: burning; animation-duration: .005s; animation-direction: alternate; animation-iteration-count: infinite; animation-timing-function: linear; transform-origin: center center; } .burning-pause { animation-play-state: paused; } .burning-run { animation-play-state: running; }
我通过JS监听click事件切换.burning-pause和.burning-run类来控制动画播放/暂停,但animation-play-state只有paused和running两种取值,没法直接让动画停止并回到第一帧,请问该怎么实现这个需求?
解决方案:重置动画属性回到初始状态
要让动画停止并回到初始帧,不能只依赖animation-play-state,核心是重置元素的动画相关样式,让它回到没有应用动画时的初始状态。下面是两种可行的实现方式:
方法1:直接通过JS修改内联样式重置动画
const turboFire = document.getElementById('turbo_fire'); turboFire.addEventListener('click', function() { // 判断当前是否在播放动画 if (this.classList.contains('burning-run')) { // 重置动画:设置animation为none,移除控制类 this.style.animation = 'none'; this.classList.remove('burning-run', 'burning-pause'); // 强制浏览器重绘(避免后续重新播放时动画不启动) void this.offsetWidth; } else { // 重新启用动画:清空内联样式,添加播放类 this.style.animation = ''; this.classList.add('burning-run'); } });
方法2:新增重置类配合切换
先在CSS里添加一个重置类:
.burning-reset { animation: none !important; /* 如果动画修改了其他属性(比如transform、opacity),这里可以显式设置初始值 */ /* 例如:transform: none; */ }
然后在JS里控制类的切换:
const turboFire = document.getElementById('turbo_fire'); turboFire.addEventListener('click', function() { if (this.classList.contains('burning-run')) { // 切换到重置状态,回到初始帧 this.classList.remove('burning-run'); this.classList.add('burning-reset'); } else { // 重新播放动画:先移除重置类,再添加播放类 this.classList.remove('burning-reset'); // 强制重绘,确保动画重新启动 void this.offsetWidth; this.classList.add('burning-run'); } });
关键说明
- 为什么需要强制重绘?浏览器会合并样式更改以优化性能,如果连续修改动画属性,可能不会触发动画重新启动。
void element.offsetWidth会强制浏览器立即计算元素尺寸,触发重绘,确保动画能正常重新开始。 - 如果你的动画修改了
transform、opacity等其他属性,在重置时可以显式设置这些属性的初始值,避免出现样式残留。
内容的提问来源于stack exchange,提问作者Vladikslavus
相关产品推荐
相关产品推荐

