css 动画可以产生多种效果,先简单介绍下 animation 的使用。
animation 属性
animation 属性是如下属性的简写属性:animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction 和 animation-fill-mode。
animation 需要调用 @keyframes 产生动画效果,看个实例
1 | // HTML |
2 | <div class="box"></div> |
3 | // CSS |
4 | @keyframes pinpon { |
5 | 0% { |
6 | background: yellow; |
7 | left: 0; |
8 | top: 0; |
9 | } |
10 | 50% { |
11 | left: 200px; |
12 | top: 150px; |
13 | } |
14 | 100% { |
15 | left: 300px; |
16 | top: 0; |
17 | background: red; |
18 | } |
19 | } |
20 | .box { |
21 | background: green; |
22 | border-radius: 50%; |
23 | height: 95px; |
24 | width: 95px; |
25 | position: absolute; |
26 | animation: pinpon 3s ease-in 1s alternate infinite forwards; |
27 | } |
28 | .box:hover{ |
29 | animation-play-state: paused; |
30 | } |
效果图
animation-name
animation-name 属性指定应用的一系列动画,每个名称代表一个由@keyframes定义的动画序列。
animation-duration
animation-duration 属性指定一个动画周期的时长。默认值为0s,表示无动画。
animation-timing-function
animation-timing-function 属性定义CSS动画在每一动画周期中执行的节奏。可能值为一或多个,初始值ease。
可取的值有:ease、ease-in、ease-out、ease-in-out、linear、cubic-bezier(x1, y1, x2, y2)、step-start、step-end、steps(number,start / end)。
animation-delay
animation-delay 属性定义动画于何时开始,即从动画应用在元素上到动画开始的这段时间的长度。初始值0s。
animation-iteration-count
animation-iteration-count 属性定义动画在结束前运行的次数可以是1次或无限循环。默认播放动画循环1次。
可取的值:
infinite:无限循环播放动画。
number:动画播放的次数不可为负值。可以用小数定义循环(0.5 将播放动画到关键帧的一半)。
animation-direction
animation-direction 属性指示动画是否反向播放。初始值 normal。
可取的值有:
normal:每个循环内动画向前循环,换言之,每个动画循环结束,动画重置到起点重新开始,这是默认属性。
reverse:反向运行动画,每周期结束动画由尾到头运行。
alternate:动画交替运行,反向运行时,动画按步后退,同时,带时间功能的函数也反向,比如,ease-in 在反向时成为ease-out。
alternate-reverse:反向交替, 反向开始交替。
animation-fill-mode
animation-fill-mode 属性用来指定在动画执行之前和之后如何给动画的目标应用样式。初始值none。
可取的值有:
none:动画执行前后不改变任何样式
forwards:目标保持动画最后一帧的样式。
backwards:动画采用相应第一帧的样式。
both:动画将会执行 forwards 和 backwards 执行的动作。
animation-play-state
animation-play-state CSS 属性定义一个动画是否运行或者暂停。初始值running。
可取的值有:
running:当前动画正在运行。
paused:当前动画以被停止。
使用keyframes定义动画
通过使用@keyframes建立两个或两个以上关键帧来实现。每一个关键帧都描述了动画元素在给定的时间点上应该如何渲染。关键帧使用百分比来指定动画发生的时间点。0%表示动画的第一时刻,100%表示动画的最终时刻。因为这两个时间点十分重要,所以还有特殊的别名:from和to。
1 | div{ |
2 | animation: pulse 5s infinite; |
3 | } |
4 | @keyframes pulse { |
5 | 0% { |
6 | background-color: #001F3F; |
7 | } |
8 | 100% { |
9 | background-color: #FF4136; |
10 | } |
11 | } |
实现简单的背景切换。