Firefox浏览器中Keyframes动画无法播放问题求助
CSS动画在Firefox中无法初始化的解决办法
问题描述
我的CSS动画在Edge和Chrome中表现符合预期,但在Firefox的移动端和桌面端均无法初始化。已尝试为animation和keyframes属性添加-moz-前缀,但问题仍未解决。预期效果为:.slogan元素从下方淡入,.consumer元素同步上移并出现两端下划线动画。
原代码如下:
.slogan { opacity: 0; transform: translateY(2.5rem); animation: fade 2s ease 0.8s forwards; } @keyframes fade { to { opacity: 1; transform: translateY(0); } } .consumer { transform: translateY(2.5rem); background: linear-gradient(currentColor 0 0) 0 100% /var(--d, 0) 1px no-repeat, linear-gradient(currentColor 0 0) 100% calc(100% - 8px) /var(--d, 0) 1px no-repeat; animation: underline 1s ease 1.5s forwards; } @keyframes underline { to { --d: 100%; background-position: 0% calc(100% - 1px), 100% calc(100% - 2px); transition: 1s, background-position 1s 1s; transform: translateY(0); } }
<div class="slogan"> <h2>Your <span class="consumer">consumer-driven</span> web hosting service.</h2> </div>
解决方案
问题原因
Firefox在处理@keyframes中同时修改CSS变量和transition属性时存在兼容性问题,直接在to关键帧内声明transition会导致动画无法触发。另外,现代Firefox已支持标准的animation和@keyframes语法,无需添加-moz-前缀。
修改后代码
调整.consumer的动画逻辑,移除transition声明,改用关键帧分步控制所有属性变化:
.slogan { opacity: 0; transform: translateY(2.5rem); animation: fade 2s ease 0.8s forwards; } @keyframes fade { to { opacity: 1; transform: translateY(0); } } .consumer { transform: translateY(2.5rem); background: linear-gradient(currentColor 0 0) 0 100% /var(--d, 0) 1px no-repeat, linear-gradient(currentColor 0 0) 100% calc(100% - 8px) /var(--d, 0) 1px no-repeat; animation: underline 2s ease 1.5s forwards; /* 延长时长模拟原transition延迟效果 */ } @keyframes underline { 0% { --d: 0; background-position: 0% 100%, 100% calc(100% - 8px); transform: translateY(2.5rem); } 50% { --d: 100%; background-position: 0% 100%, 100% calc(100% - 8px); transform: translateY(0); } 100% { --d: 100%; background-position: 0% calc(100% - 1px), 100% calc(100% - 2px); transform: translateY(0); } }
<div class="slogan"> <h2>Your <span class="consumer">consumer-driven</span> web hosting service.</h2> </div>
关键修改点
- 移除
@keyframes underline中的transition声明,通过关键帧分步控制背景位置和CSS变量,避免Firefox兼容性冲突 - 将
.consumer的动画时长调整为2s,模拟原transition的1s延迟效果,保证动画节奏与预期一致 - 明确写出
0%关键帧的初始状态,让Firefox能清晰识别动画起始值
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

