如何获取Web Animation关键帧间任意时刻的CSS或样式信息?
获取Web Animations API动画任意时刻的状态样式
这个问题问得很实用!如果你用的是Web Animations API(就像你给出的示例那样),想要获取动画任意时刻的状态样式,分两种场景来处理就好:
一、实时获取动画运行中的当前样式
当动画正在运行时,浏览器会把动画的中间状态实时同步到元素的计算样式里,直接用getComputedStyle()就能拿到当前时刻的真实样式:
<div class="thing"></div> <style> html { height: 100%; } body { display: flex; justify-content: center; align-items: center; height: 100%; background-color: #0a2933; } .thing { height: 100px; width: 100px; background-color: orange; } </style> <script> const thingEl = document.querySelector('.thing'); const animation = thingEl.animate([ { transform: 'rotate(0) scale(1)', backgroundColor: 'orange' }, { transform: 'rotate(180deg) scale(3)', backgroundColor: 'blue' }, { transform: 'rotate(360deg) scale(1)', backgroundColor: 'orange' } ], { duration: 3000, iterations: Infinity }); // 每隔100ms打印一次当前样式,观察实时状态 setInterval(() => { const computedStyle = getComputedStyle(thingEl); console.log('当前transform:', computedStyle.transform); console.log('当前背景色:', computedStyle.backgroundColor); }, 100); </script>
二、获取指定任意时刻的样式(比如还没运行到的时间点)
如果想知道动画在某个特定时间点(比如动画进行到第1.5秒时)的状态,哪怕动画没运行到那里,可以通过暂停动画、手动设置时间点的方式来获取:
const thingEl = document.querySelector('.thing'); const animation = thingEl.animate([ { transform: 'rotate(0) scale(1)', backgroundColor: 'orange' }, { transform: 'rotate(180deg) scale(3)', backgroundColor: 'blue' }, { transform: 'rotate(360deg) scale(1)', backgroundColor: 'orange' } ], { duration: 3000, iterations: Infinity }); // 先暂停动画,避免自动运行干扰状态获取 animation.pause(); // 把动画时间跳转到目标时刻(这里是1500ms,也就是动画的中间点) animation.currentTime = 1500; // 此时获取计算样式,就是该时刻的动画状态 const computedStyle = getComputedStyle(thingEl); console.log('1500ms处的transform:', computedStyle.transform); console.log('1500ms处的背景色:', computedStyle.backgroundColor); // 如果之后要继续动画,调用play()即可 // animation.play();
小提醒
- 正如你提到的,Web Animations API仅在部分浏览器/平台支持,使用前可以先做兼容性检测:
if (!Element.prototype.animate) { console.warn('当前浏览器不支持Web Animations API,请考虑降级方案'); } - 设置
currentTime后,哪怕动画处于暂停状态,元素的样式也会更新到对应时间点的动画状态,用完记得根据需求重置或恢复动画哦。
内容的提问来源于stack exchange,提问作者arxpoetica
相关产品推荐
相关产品推荐

