
通过设置 `animation-fill-mode: forwards`,可让 css 动画在播放完毕后保留最后一帧的样式,从而实现元素(如块级元素)在点击按钮上升并永久停留在目标位置(如 `margin-top: -25px`)的效果。
在 CSS 动画中,动画默认仅作用于播放期间——一旦动画结束,元素会立即“回弹”到其原始样式(即动画开始前的状态)。这正是原代码中 .block 元素在 up 动画执行完毕后无法维持 margin-top: -25px 的根本原因。
解决方法非常简洁:为动画应用类 .animation 添加 animation-fill-mode: forwards 声明。该属性指示浏览器在动画结束后,将元素的样式保持在 100% 关键帧所定义的状态,而非恢复初始值。
以下是完整、可直接运行的优化代码:
.block {
width: 100px;
height: 100px;
background: green;
margin-top: 0; /* 显式声明初始值,增强可维护性 */
}
.animation {
animation: up 750ms ease-out;
animation-fill-mode: forwards; /* ✅ 关键:锁定最终状态 */
}
@keyframes up {
0% {
margin-top: 0;
}
100% {
margin-top: -25px;
}
}⚠️ 注意事项:
立即学习“前端免费学习笔记(深入)”;
- animation-fill-mode: forwards 仅影响动画结束后的样式保持,不影响动画播放过程或触发条件;
- 若需支持多次点击(例如“上/下”切换),应配合 removeAnimation() 或切换类名(如 .animation-up / .animation-down),并注意重置 animation 属性以避免动画不触发(可借助 animation: none 临时清除);
- 推荐使用 transform: translateY(-25px) 替代 margin-top 实现位移——它性能更优(不触发重排),且与 forwards 兼容性一致;
- 所有现代浏览器均支持 animation-fill-mode(包括 Chrome 43+、Firefox 16+、Safari 9+、Edge 12+),无需前缀。
总结:animation-fill-mode: forwards 是控制动画“停留行为”的标准且可靠的 CSS 方案,是实现 UI 交互中状态持久化的必备技巧。










