调整CSS动画速度时如何避免移动元素重置位置,保持动画流畅运行
问题根因
你当前通过切换CSS类修改animation-duration的实现,会触发浏览器重新加载动画规则,导致动画从头开始播放,所以出现图片位置重置的问题。
解决方案
使用Web Animations API直接修改动画的播放速率,无需切换CSS类,调速时完全保留当前动画进度,实现平滑衔接。
修改后代码
CSS 代码
.slow{ width: 3500px; height: 195px; background-image: url(https://layerslider.com/wp-content/uploads/layerslider/Back-To-The-80s/hills-far-2500x2-1-2048x164.png); background-size: 3500px 195px; background-position: -3500px 0; animation: run linear infinite; animation-duration: 100s; } @keyframes run { from {background-position: -3500px 0;} to {background-position: 0 0;} }
JS 代码
const animElement = document.getElementById("animation"); document.getElementById("fast").addEventListener("click", gofaster); function gofaster() { const animation = animElement.getAnimations()[0]; // 10倍速对应原需求10秒播完全程 animation.playbackRate = 10; } document.getElementById("slow").addEventListener("click", goslower); function goslower() { const animation = animElement.getAnimations()[0]; // 1倍速对应原需求100秒播完全程 animation.playbackRate = 1; }
HTML 代码(无修改)
<div id="animation" class="slow"></div> <button id="fast">faster</button> <button id="slow">slower</button>
实现说明
Element.getAnimations()可以获取元素上所有正在运行的动画实例,playbackRate属性用于控制动画播放速度,默认值为1,数值越大播放速度越快。直接修改该属性不会中断或重置动画,会从当前进度直接按新速率继续运行,完全符合调速不重置位置的需求。
内容的提问来源于stack exchange,提问作者Sahib Yar
相关产品推荐
相关产品推荐

