CSS 的关键帧和动画是如何工作
如果要给元素添加动画,你需要了解 animation 属性以及 @keyframes 规则。 animation 属性控制动画的外观,@keyframes 规则控制动画中各阶段的变化。 总共有 8 个 animation 属性。
-
animation-name
用来设置动画的名称,也就是我们稍后要在 @keyframes 里用到的名称。 -
animation-duration
设置动画所花费的时间。
@keyframes 可以通过设置特定时间点的行为来创建动画。 为此,我们只需要给持续时间内的特定帧(从 0% 到 100%)加上 CSS 规则。 如果用一部电影来做类比,那么 CSS 里面的 0% 关键帧就像是电影里面的开场镜头;100% 关键帧就像是电影里的片尾,就是那个之后会出现演职人员列表的片尾。 在动画设定的时间内,CSS 会根据关键帧的规则来给元素添加动画效果。 100% 位置的 CSS 属性就是元素最后的样子,相当于电影里的演职员表或者鸣谢镜头。 然后CSS 应用魔法来在给定的时间内转换元素以使其脱离场景。 下面举例说明 @keyframes 和动画属性的用法:
#anim {
animation-name: colorful;
animation-duration: 3s;
}
@keyframes colorful {
0% {
background-color: blue;
}
100% {
background-color: yellow;
}
}
id 为 anim 的元素,我们在代码中将它的 animation-name 设置为 colorful,同时设置 animation-duration 为 3 秒。 然后我们把 @keyframes 规则添加到名为 colorful 的动画属性上。 在动画开始时(0%)的背景颜色为蓝色,在动画结束时(100%)的背景颜色为黄色。 注意我们不只可以设置开始和结束,而是从 0% 到 100% 间的任意位置都可以设置。
- @keyframes 规则的用法。
还有一个常用的动画属性是 animation-iteration-count,这个属性允许你控制动画循环的次数。 下面是一个例子:
animation-iteration-count: 3;
在这里动画会在运行 3 次后停止,如果想让动画一直运行,可以把值设置成 infinite。
<style>
#ball {
width: 100px;
height: 100px;
margin: 50px auto;
position: relative;
border-radius: 50%;
background: linear-gradient(
35deg,
#ccffff,
#ffcccc
);
animation-name: bounce;
animation-duration: 1s;
animation-iteration-count: infinite;
}
@keyframes bounce{
0% {
top: 0px;
}
50% {
top: 249px;
width: 130px;
height: 70px;
}
100% {
top: 0px;
}
}
</style>
<div id="ball"></div>
注释:把 animation-iteration-count 属性改成 infinite,使右边的球一直跳跃。
同样的,我们可以利用无限动画计数制作心跳:
心跳动画的每一秒包含两个部分。 heart 元素(包括 :before 和 :after)使用 transform 属性改变其大小,背景 div 使用 background 属性改变其颜色。
<style>
.back {
position: fixed;
padding: 0;
margin: 0;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: white;
animation-name: backdiv;
animation-duration: 1s;
animation-iteration-count:infinite;
}
.heart {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: pink;
height: 50px;
width: 50px;
transform: rotate(-45deg);
animation-name: beat;
animation-duration: 1s;
animation-iteration-count:infinite;
}
.heart:after {
background-color: pink;
content: "";
border-radius: 50%;
position: absolute;
width: 50px;
height: 50px;
top: 0px;
left: 25px;
}
.heart:before {
background-color: pink;
content: "";
border-radius: 50%;
position: absolute;
width: 50px;
height: 50px;
top: -25px;
left: 0px;
}
@keyframes backdiv {
50% {
background: #ffe6f2;
}
}
@keyframes beat {
0% {
transform: scale(1) rotate(-45deg);
}
50% {
transform: scale(0.6) rotate(-45deg);
}
}
</style>
<div class="back"></div>
<div class="heart"></div>
注释:给 back class 和 the heart class 添加 animation-iteration-count 属性,将属性值设置为 infinite,使心保持跳动。 heart:before 和 heart:after 所选择的元素则不需要添加动画属性。