CSS系列之动画和过渡
yuanyuanbyte opened this issue · 0 comments
CSS 中动画有几种?
两种!一种是过渡动画,一种是关键帧动画。
过度动画只能定义「开始」和「结束」两个状态。
关键帧动画可以定义「多个状态」。
如何写「过渡动画」?
使用 transition 属性即可撰写过渡动画。比如看下面的例子:
<html>
<body>
<div class="section">hello</div>
</body>
</html>
.section{
width: 100px;
background-color: black;
color: white;
transition: 2s;
}
.section:hover{
width: 300px;
}
上面代码的含义:
div 在平时状态下宽度为 100 像素,在鼠标悬浮其上的时候,宽度为 300 像素。
但是可以看到,我们通过加入了transition: 2s;
这个属性,让宽度的变化不是瞬间完成的,而是在 2s 内逐步完成的。
这就是 transition 动画——也就是我们的过渡动画。
如何写关键帧动画?
使用 @keyframes
关键字定义动画。
下面的例子将在动画完成 25%,完成 50% 以及动画完成 100% 时更改 <div>
元素的背景颜色::
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}
@keyframes example {
0% {background-color: red;}
25% {background-color: yellow;}
50% {background-color: blue;}
100% {background-color: green;}
}
</style>
</head>
<body>
<p><b>注释:</b>本例在 Internet Explorer 9 以及更早的版本中无效。</p>
<div></div>
</body>
</html>
我们用百分比来规定变化发生的时间,或用关键词 "from" 和 "to",等同于 0% 和 100%。
0% 是动画的开始,100% 是动画的完成。
为了得到最佳的浏览器支持,我们最好定义 0% 和 100% 选择器。
使用关键字动画,需要在指定动画的元素上定义animation-name
:动画名称,和animation-duration
:动画完成一个周期所花费的时间。
animation-name
:动画名称,将声明的动画名称和@keyframes
绑定用来描述动画;
animation-iteration-count
:规定动画被播放的次数。默认是 1。该属性设置为 infinite 使动画永远持续下去。
animation-direction
:指定是否应该轮流反向播放动画。该属性设置为 alternate 可实现来回运动(动画在奇数次(1、3、5...)正向播放,在偶数次(2、4、6...)反向播放)
一个来回运动的例子:
<div class="test">1</div>
.test {
background-color: rgb(50, 188, 131);
animation-name: slidein;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-direction: alternate;
}
@keyframes slidein {
from {
margin-left: 100%;
width: 0;
}
to {
margin-left: 0%;
width: 500px;
}
}