CSS动画是一个强大的工具,允许开发者创建平滑、吸引人的过渡效果。animation
属性是 CSS 中用于控制动画的关键属性,它是多个动画相关属性的简写形式。下面是对 animation
属性的详细解释:
animation 属性
animation
属性是以下动画相关属性的简写:
animation-name
animation-duration
animation-timing-function
animation-delay
animation-iteration-count
animation-direction
animation-fill-mode
animation-play-state
各属性的详解
-
animation-name
- 定义要绑定到选择器的关键帧名称。
- 例如:
animation-name: myAnimation;
-
animation-duration
- 定义动画完成一个周期所需的时间。
- 例如:
animation-duration: 2s;
-
animation-timing-function
- 定义动画的速度曲线。
- 常见的值有:
linear
、ease
、ease-in
、ease-out
、ease-in-out
、cubic-bezier()
等。 - 例如:
animation-timing-function: ease-in-out;
-
animation-delay
- 定义动画开始前等待的时间。
- 例如:
animation-delay: 1s;
-
animation-iteration-count
- 定义动画播放的次数。可以是具体数字,也可以是
infinite
。 - 例如:
animation-iteration-count: 3;
或animation-iteration-count: infinite;
- 定义动画播放的次数。可以是具体数字,也可以是
-
animation-direction
- 定义动画是否应该轮流反向播放。
- 可能的值有:
normal
、reverse
、alternate
、alternate-reverse
。 - 例如:
animation-direction: alternate;
-
animation-fill-mode
- 定义动画在播放之前和之后如何应用样式。
- 可能的值有:
none
、forwards
、backwards
、both
。 - 例如:
animation-fill-mode: forwards;
-
animation-play-state
- 定义动画是否正在运行或已暂停。
- 可能的值有:
running
和paused
。 - 例如:
animation-play-state: paused;
使用 animation 简写属性
你可以将上述所有属性组合到 animation
属性中,以简化代码。例如:
div {
animation: myAnimation 2s ease-in-out 1s infinite alternate forwards;
}
在这个例子中,myAnimation
是关键帧名称,2s
是动画持续时间,ease-in-out
是速度曲线,1s
是延迟时间,infinite
是迭代次数,alternate
是动画方向,forwards
是填充模式。
关键帧定义
要使用 animation
属性,你还需要定义关键帧。关键帧使用 @keyframes
规则来定义。例如:
@keyframes myAnimation {
0% {background-color: red;}
50% {background-color: blue;}
100% {background-color: green;}
}
在这个例子中,myAnimation
关键帧定义了背景色从红色变为蓝色,然后再变为绿色的动画。
通过结合使用 animation
属性和 @keyframes
规则,你可以创建出丰富多样的动画效果。