CSS animation-fill-mode 属性 确定在执行 CSS 动画之前和之后应如何将样式应用于 CSS 动画的目标。
使用简写属性 animation 一次设置所有动画设置通常很方便。
可能的值
CSS 属性 animation-fill-mode 可以具有以下值之一:
none - 当动画不执行时,它不会对目标应用任何样式。相反,该元素将根据任何其他现有的 CSS 规则显示。此行为表示默认设置。
forwards - 在执行过程中检测到的最终关键帧设置的计算值将保留在目标上。animation-direction 和 animation-iteration-count 的值确定最终的关键帧:
动画方向 | 动画迭代计数 | 遇到的最后一个关键帧 |
---|---|---|
normal | even or odd | 100% or to |
reverse | even or odd | 0% or from |
alternate | even | 0% or from |
alternate | odd | 100% or to |
alternate-reverse | even | 100% or to |
alternate-reverse | odd | 0% or from |
backwards - 一旦动画应用于目标,它将应用在第一个适当的关键帧中指定的值,并在动画延迟期间保持它们。animation-direction 值确定第一个合适的关键帧:
动画方向 | 第一个相关关键帧 |
---|---|
normal or alternate | 0% or from |
reverse or alternate-reverse | 100% or to |
both - 动画将在前进和后退方向上都遵循规则,从而有效地扩展了两个方向的动画属性。
注: 如果在 animation-* 属性上指定了多个逗号分隔的值,则这些值将按照动画名称s 出现的顺序应用于动画。
语法
animation-fill-mode = <single-animation-fill-mode>#
<single-animation-fill-mode> = none | forwards | backwards | both;
适用于
所有 HTML 元素 ::before 和 ::after 伪元素。
CSS animation-fill-mode - 向后值
以下示例演示了 animation-fill-mode。
- 在给出的 CSS 示例中,animation-fill-mode 属性设置为向后。
- 当将鼠标悬停在 .animation-demo 元素上时,将触发增长动画。
- 它将圆圈放大 1 秒。animation-fill-mode: backwards 属性可确保在悬停状态结束时,元素在动画开始之前保持其初始状态。
<html>
<head>
<style>
.animation-demo {
width: 200px;
height: 200px;
margin-left: 150px;
margin-top: 150px;
background-color: #2799db;
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
color: white;
font-size: 20px;
transition: all 1s ease;
}
@keyframes grow {
0% {
transform: scale(1);
}
100% {
transform: scale(1.5);
}
}
.animation-demo:hover {
animation-name: grow;
animation-duration: 1s;
animation-fill-mode: backwards;
}
</style>
</head>
<body>
<div class="animation-demo">Hover over this!</div>
</body>
</html>
CSS animation-fill-mode - 转发值
以下示例演示了 animation-fill-mode。
- 在此示例中,animation-fill-mode: forwards; 应用于初始动画,以确保元素在动画完成后保持其最终状态(完全可见)。
- 当鼠标指针悬停在元素上时,动画会反转,因为在使用 animation-fill-mode: forwards; 悬停时分配了一个单独的动画,保持最终状态,以便即使在悬停动画完成后,元素仍保持在其最终位置。
- 此属性在动画之后或悬停动画之后保留元素的视觉状态,从而保持事物看起来相同,而不会回到以前的样子。
<html>
<head>
<style>
@keyframes slidein {
from {
margin-left: 100%;
width: 300%;
}
to {
margin-left: 0%;
width: 100%;
}
}
@keyframes slideback {
from {
margin-left: 0%;
width: 100%;
}
to {
margin-left: 100%;
width: 300%;
}
}
div {
width: 100px;
height: 100px;
background-color: red;
position: relative;
animation-name: slidein;
animation-duration: 6s;
animation-fill-mode: forwards;
font-size: 20px;
color: white;
}
div:hover {
animation-name: slideback;
animation-duration: 6s;
animation-fill-mode: forwards;
}
</style>
</head>
<body>
<div>Hover Over This!</div>
</body>
</html>