# CSS3教程 - 13 动画
CSS 中的动画主要包括两种,一种是过渡动画, 例如颜色、大小、透明度的慢慢变化;另一种是帧动画,通过设置多个关键帧,通过在关键帧之间的切换实现动画。
# 13.1 过渡动画
过渡动画是 状态之间的渐变,当 CSS 属性的值发生变化时,浏览器会在指定的时间内逐步变化,而不是立即跳转到新值。
# 1 过渡的使用
直接举个栗子:
<!DOCTYPE html>
<html>
<head>
<style>
.box1 {
width: 600px;
height: 200px;
background-color: lightgray;
}
.box2 {
width: 100px;
height: 100px;
background-color: skyblue;
}
.box1:hover .box2 {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">foooor.com</div>
</div>
</body>
</html>
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
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
- 上面的代码很简单,就是 box1 中嵌套了 box2,当鼠标悬浮在 box1 上的时候,box2 的尺寸就会变成 200px。
显示如下:
但是鼠标悬浮的时候,box2 的尺寸是瞬间变大的,没有过渡效果,下面就给鼠标悬浮添加过渡效果。
.box2 {
width: 50px;
height: 50px;
background-color: skyblue;
transition-property: width, height; /* 指定要执行过渡的属性 */
transition-duration: 1s; /* 指定过渡效果的持续时间 */
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- 上面给 box2 添加了过渡相关的属性,
transition-property
指定要指定过渡的属性,多个属性使用,
分隔,如果所有属性都需要过渡,则使用all
关键字(transition-property: all;
); transition-duration
:指定过渡效果的持续时间,单位可以使用秒(s
)和毫秒(ms
)。
显示如下:
如果多个属性的过渡时间不同,那么可以分别指定过渡时间:
transition-property: width, height; /* 指定要执行过渡的属性 */
transition-duration: 1s, 500ms; /* 指定过渡效果的持续时间 */
1
2
2
- 上面为宽度指定过渡时间为
1s
,高度的过渡时间为500ms
。
CSS 中大部分属性都支持过渡效果,从一个有效数值过渡的另一个有效数值,需要注意,有的值默认是 auto
是不可以的,需要设置为数值才可以。
颜色也是可以过渡,例如将鼠标悬浮后 ,box2 的颜色设置为粉色:
.box2 {
width: 100px;
height: 100px;
background-color: skyblue;
transition-property: all; /* 指定要执行过渡的属性 */
transition-duration: 1s; /* 指定过渡效果的持续时间 */
}
.box1:hover .box2 {
width: 200px;
height: 200px;
background-color: lightpink;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
- 上面设置所有属性都指定多度动画,然后设置鼠标悬浮后,box2 的颜色为粉色。
显示如下:
# 2 过渡时序函数
过渡时序函数用于定义过渡效果的速度曲线。它决定了属性值在过渡过程中如何随时间变化,从而影响动画的流畅度和视觉效果。
CSS 提供了一些预定义的时序函数,适用于不同的动画效果:
内容未完......