如何在原生JS的Element.animate方法中设置animation-fill-mode
解决Element.animate()的填充模式及hover状态切换问题
Web Animations API 中,对应 CSS animation-fill-mode: forwards 的配置是 timing 对象里的 fill 属性,而非你尝试的 animation-fill-mode。将其设为 "forwards" 即可让动画结束后元素保持最后一帧的状态。
修正后的完整代码
const quotemove = [ { transform: "translate(0vw) rotate(0deg)" }, { transform: "translate(80vw) rotate(180deg)" } ]; const quotetiming = { duration: 1000, iterations: 1, fill: "forwards" // 正确设置填充模式 }; const quoteholders = document.getElementsByClassName("quote"); // 存储每个元素的动画实例,避免多动画叠加混乱 const animationMap = new Map(); for(let i = 0; i < quoteholders.length; i++) { let quoteholder = quoteholders.item(i); const quotemark = quoteholder.querySelector(".quotationmark"); quoteholder.addEventListener("mouseover", () => { // 取消之前未完成的反向动画 const prevAnim = animationMap.get(quotemark); if(prevAnim) prevAnim.cancel(); const animation = quotemark.animate(quotemove, quotetiming); animationMap.set(quotemark, animation); }); // 添加mouseout的反向动画逻辑 quoteholder.addEventListener("mouseout", () => { const prevAnim = animationMap.get(quotemark); if(prevAnim) prevAnim.cancel(); // 定义反向动画关键帧 const reverseMove = [ { transform: "translate(80vw) rotate(180deg)" }, { transform: "translate(0vw) rotate(0deg)" } ]; const reverseAnim = quotemark.animate(reverseMove, quotetiming); animationMap.set(quotemark, reverseAnim); // 动画结束后清理实例 reverseAnim.onfinish = () => { animationMap.delete(quotemark); }; }); }
兼容性替代方案(若fill属性无效)
如果遇到环境不支持fill属性的情况,可以直接在动画结束时将最终状态写入元素行内样式:
// mouseover动画中添加状态固化逻辑 const animation = quotemark.animate(quotemove, quotetiming); animation.onfinish = () => { quotemark.style.transform = "translate(80vw) rotate(180deg)"; }; // mouseout动画中重置样式 reverseAnim.onfinish = () => { quotemark.style.transform = ""; animationMap.delete(quotemark); };
关键注意点
- 存储动画实例是为了避免鼠标快速移入移出时,多个动画叠加导致的状态错乱,每次触发新动画前需取消旧动画。
- 反向动画的关键帧要和正向动画严格对应,保证状态切换的连贯性。
内容的提问来源于stack exchange,提问作者Chspsa
相关产品推荐
相关产品推荐

