
通过为动画添加 animation-fill-mode: forwards,可使元素在 css 动画执行完毕后保留最后一帧的样式(如 margin-top: -25px),避免动画回退到初始状态。
在使用 CSS @keyframes 定义动画时,浏览器默认会在动画播放结束后将元素样式重置为动画前的状态(即“回填”为原始值)。例如,你的 .animation 类触发了一个从 margin-top: 0px 上移到 margin-top: -25px 的动画,但若不显式声明动画结束后的状态保持策略,动画一结束,元素会立刻“弹回”原位。
解决方法是为动画规则添加 animation-fill-mode: forwards:
.animation {
animation: up 750ms;
animation-fill-mode: forwards; /* 关键:保持 100% 关键帧的样式 */
}该属性告诉浏览器:动画结束后,元素应维持最后一帧(即 100%)所定义的样式,而非恢复初始状态。配合你已定义的 @keyframes,即可稳定停留在 margin-top: -25px。
✅ 补充说明:
立即学习“前端免费学习笔记(深入)”;
- forwards 仅影响动画结束后的样式保持,不影响动画播放过程;
- 若需同时保持动画开始前的状态(如鼠标悬停前预设样式),可结合 backwards 或 both,但本例中只需 forwards;
- animation-fill-mode 是 animation 复合属性的子属性,也可简写为:
.animation { animation: up 750ms forwards; /* 写在 animation 值末尾即可 */ }
⚠️ 注意事项:
- 确保 animation-fill-mode 应用于触发动画的类(如 .animation),而非基础类(如 .block);
- 若后续需再次触发动画(如重复点击上移),当前方案会因 .animation 类已存在而无效果;此时建议配合 animation-play-state 或使用 removeClass().addClass() 重置,或改用 animation: none 临时清除再应用;
- 替代方案(现代推荐):优先考虑使用 transform: translateY(-25px) 替代 margin-top,性能更优且避免文档流扰动。
综上,animation-fill-mode: forwards 是实现“动画定格在终点”的标准、简洁且兼容性良好的解决方案。










