直接设置 animation-play-state: paused 或 running 即可暂停或继续 CSS 动画,无需 JavaScript;该属性仅对已声明 animation-name 和有效时长的元素生效,暂停后恢复会从当前帧继续而非重播。

怎么用 animation-play-state 暂停和继续 CSS 动画
直接设置元素的 animation-play-state 属性为 paused 或 running 即可控制播放状态,不需要 JavaScript 也能生效,但通常配合 JS 动态切换。
注意:这个属性只对已声明了 animation-name 和有效时长(如 animation-duration)的元素起作用;纯 @keyframes 定义本身不触发动画。
-
animation-play-state: running—— 正常播放(默认值) -
animation-play-state: paused—— 暂停在当前帧,不会重置计时器 - 多个动画可分别控制:比如
animation-play-state: running, paused对应两个动画
JavaScript 中如何动态切换播放状态
通过修改 style.animationPlayState(JS 驼峰写法)或 style.cssText 设置内联样式,是最常用且兼容性好的方式。
关键点:暂停后再次设为 running,动画会从暂停处继续,不是从头开始 —— 这和 animation-fill-mode、animation-delay 等行为无关,是该属性本身的语义。
立即学习“前端免费学习笔记(深入)”;
const box = document.querySelector('.animated-box');
box.style.animationPlayState = 'paused'; // 暂停
// …… 之后
box.style.animationPlayState = 'running'; // 继续,从暂停帧接着走
常见失效原因和坑
写了 animation-play-state: paused 却没效果?大概率是下面几个问题之一:
- 元素还没开始动画:比如
animation-delay还没到时间,此时设paused不可见;可先设animation-delay: 0或触发重排(如读取offsetHeight)强制启动 - CSS 优先级被覆盖:检查是否有更高优先级的规则(如 !important 或更具体的选择器)把状态又设回
running - 动画已被移除:JS 中若执行了
el.style.animation = 'none',再设animationPlayState就无效了 -
浏览器不支持:IE10+、Edge 12+、Chrome 43+、Firefox 16+ 都支持;Safari 9+ 开始支持,旧版 Safari 需用
-webkit-animation-play-state
配合 animationiteration 事件做分段控制
如果想在每次循环结束时暂停,或点击后继续下一轮,可以监听 animationiteration 事件,再手动切状态。注意:这个事件只在 animation-iteration-count > 1 且动画未被暂停时触发。
const el = document.querySelector('.looping');
el.addEventListener('animationiteration', () => {
if (shouldPauseOnIteration) {
el.style.animationPlayState = 'paused';
}
});
真正容易被忽略的是:暂停后,animationiteration 不会再触发;而恢复 running 后,剩余循环次数仍按原始设定走(比如设了 3 次,暂停两次后继续,只会再执行一次)。










