CSS动画只执行一次并停在最后一帧,需同时设置animation-iteration-count: 1和animation-fill-mode: forwards;简写形式为animation: name duration timing-function delay iteration-count fill-mode,其中fill-mode必须置末。

CSS 动画默认只执行一次,但如果你看到它反复播放,通常是因为设置了 animation-iteration-count: infinite 或其他循环相关属性。要确保动画只执行一次,并让最终状态保留(即“停在最后一帧”),关键在于正确设置两个属性:animation-iteration-count 和 animation-fill-mode。
用 animation-iteration-count: 1 显式声明——即使不写,默认也是 1,但显式写出更清晰、可维护,也避免被其他样式或重置规则覆盖。
animation-iteration-count: 1;
animation-iteration-count: infinite; 或遗漏该声明(虽默认为 1,但建议显式声明)动画结束后元素会“弹回”初始样式,除非你告诉它“停在最后一帧”。这时要用 animation-fill-mode: forwards:
forwards:动画结束后,元素保持最后一帧的 CSS 属性值forwards 不会影响动画开始前的状态;如需同时保留起始帧,可用 both
animation-fill-mode: forwards; 配合 transform: translateX(100px); 的动画,结束后元素就真正在右侧停住推荐使用 animation 简写属性,一并控制时长、函数、延迟、次数和 fill mode:
立即学习“前端免费学习笔记(深入)”;
element {
animation: slideIn 0.4s ease-out 1 forwards;
}
@keyframes slideIn {
from { opacity: 0; transform: translateX(-20px); }
to { opacity: 1; transform: translateX(0); }
}其中 1 是 iteration count,forwards 是 fill-mode —— 顺序不能错(简写中 fill-mode 必须放在最后)。
容易忽略但影响效果的细节:
to 或最后一帧,forwards 可能不生效 —— 确保 keyframes 有明确的终点声明animation-play-state: paused 或 JS 中调用 el.style.animation = 'none' 会中断或清空动画状态,慎用以上就是css动画如何只执行一次_移除循环并控制fill mode的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号