5.1 基本使用

第一步:定义关键帧(定义动画)

  1. 简单方式定义:
1
2
3
4
5
6
7
8
9
10
/*写法一*/
@keyframes 动画名 {
from {
/*property1:value1*/
/*property2:value2*/
}
to {
/*property1:value1*/
}
}
  1. 完整方式定义:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@keyframes 动画名 {
0% {
/*property1:value1*/
}
20% {
/*property1:value1*/
}
40% {
/*property1:value1*/
}
60% {
/*property1:value1*/
}
80% {
/*property1:value1*/
}
100% {
/*property1:value1*/
}
}

第二步:给元素应用动画,用到的属性如下:

  1. animation-name :给元素指定具体的动画(具体的关键帧)
  2. animation-duration :设置动画所需时间
  3. animation-delay :设置动画延迟
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>01_基本使用</title>
<style>
.outer {
width: 1000px;
height: 100px;
border: 1px solid black;
}
/* 定义一个动画(定义一组关键帧)—— 第一种方式 */
@keyframes wangyoudong {
/* 第一帧 */
from {

}
/* 最后一帧 */
to {
transform: translate(900px);
background-color: red;
}
}
/* 定义一个动画(定义一组关键帧)—— 第二种方式 */
@keyframes wangyoudong2 {
/* 第一帧 */
0% {

}
/* 29% {
background-color: red;
} */
/* 48% {
background-color: orange;
} */
/* 88% {
background-color: yellow;
} */
/* 最后一帧 */
100% {
transform: translate(900px) rotate(360deg);
background-color: purple;
border-radius: 50%;
}
}
.inner {
width: 100px;
height: 100px;
background-color: deepskyblue;
/* 应用动画到元素 */
animation-name: wangyoudong2;
/* 动画持续的时间 */
animation-duration: 3s;
/* 动画延迟时间 */
animation-delay: 0.2s;
}

</style>
</head>
<body>
<div class="outer">
<div class="inner"></div>
</div>
</body>
</html>

5.2 动画的其他属性

  • animation-timing-function ,设置动画的类型,常用值如下:
    1. ease : 平滑动画 —— 默认值
    2. linear : 线性过渡
    3. ease-in : 慢 → 快
    4. ease-out : 快 → 慢
    5. ease-in-out : 慢 → 快 → 慢
    6. step-start : 等同于 steps(1, start)
    7. step-end : 等同于 steps(1, end)
    8. steps( integer,?) : 接受两个参数的步进函数。第一个参数必须为正整数,指定函数的步数。第二个参数取值可以是 start 或 end ,指定每一步的值发生变化的时间点。第二个参数默认值为 end 。
    9. cubic-bezie ( number, number, number, number): 特定的贝塞尔曲线类型。
  • animation-iteration-count ,指定动画的播放次数,常用值如下:
    1. number :动画循环次数
    2. infinite : 无限循环
  • animation-direction ,指定动画方向,常用值如下:
    1. normal : 正常方向 (默认)
    2. reverse : 反方向运行
    3. alternate : 动画先正常运行再反方向运行,并持续交替运行
    4. alternate-reverse : 动画先反运行再正方向运行,并持续交替运行
  • animation-fill-mode ,设置动画之外的状态
    1. forwards : 设置对象状态为动画结束时的状态
    2. backwards : 设置对象状态为动画开始时的状态
  • animation-play-state ,设置动画的播放状态,常用值如下:
    1. running : 运动 (默认)
    2. paused : 暂停

5.3动画复合属性

只设置一个时间表示 duration ,设置两个时间分别是: duration 和 delay ,其他属性没有数量和顺序要求。

备注: animation-play-state 一般单独使用。

1
2
3
.inner {
animation: atguigu 3s 0.5s linear 2 alternate-reverse forwards;
}