CSS3中有两种方式实现动画,transition和animation+@keyframe。
两者的作用机制不一样:transition定义在可能要进行动画的元素上,对某些CSS属性进行监听,一旦CSS改变则进行动画;animation定义在马上要进行动画的元素上,一旦定义动画即进行。
比如当鼠标悬浮的时候,某元素由红色改为绿色。使用transition和animation实现的共同代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div {
width: 300px;
height: 200px;
background-color: red;
/*不同的代码*/
}
div:hover {
/*不同的代码*/
}
</style>
</head>
<body>
<div></div>
</body>
</html>
使用transition的代码量更少,简介直观。
div {
width: 300px;
height: 200px;
background-color: red;
transition: background-color 2s;
}
div:hover {
background-color: green;
}
其中transition可作为监听器,监听background-color的改变,一旦改变则之前的值作为初始状态,后来的值作为终止状态,进行整个过渡动画。
使用animation先要定义各种时间段的状态,这里只需要定义开始时间和结束时间,这个定义放在@keyframes中,anmation再调用这个keyframes。
div {
width: 300px;
height: 200px;
background-color: red;
-webkit-animation: test1 2s forwards;
}
div:hover {
-webkit-animation: test2 2s forwards;
}
@-webkit-keyframes test1 {
from {background-color: green;}
to {background-color: red;}
}
@-webkit-keyframes test2 {
from {background-color: red;}
to {background-color: green;}
}
这里定义了两套动画和关键帧,一套应用于普通状态,一套应用于鼠标悬浮状态。而且开始状态的CSS和元素之前的CSS没关系,需要重新定义。更需要注意的是,animation的表现和transition有一点不同,在页面加载后会先执行普通状态下的动画一次。乍看一下,似乎animation完全不如transition好用,对于这个简单的需求确实如此,但animation可以应付一些更复杂的需求。
以下先从简单的开始,也就是transition。
transition的意思不是动画,而是过渡,从一个状态过渡到另一个状态。这意味着这个动画的执行包含三个要素,初始状态、过渡、终止状态。简单的结构意味着简单的实现和受限制的功能。transiton只包含四个属性:
- transition-property: 要监听的CSS属性,如果有多个属性,用逗号分隔,且不能用transition简写。
- transition-duration: 动画执行的时间。
- transition-timing-function: 动画执行的方式。linear(匀速) | ease(先快后慢,默认值) | ease-in(先慢后快) | ease-out(先快后慢) | ease-in-out(先慢中快后慢) | cubic-bezier(n, n, n, n) (贝塞尔曲线)
- transition-delay: 动画延迟执行的时间。
首先用transition-property监听多个属性,代码如下:
div {
width: 300px;
height: 200px;
background-color: red;
transition-property: background-color, width;
transition-duration: 2s;
}
div:hover {
background: green;
width: 500px;
}
如果想移出鼠标不要立即执行动画,而是等0.5秒,则代码如下:
div {
width: 300px;
height: 200px;
background-color: red;
transition-property: background-color, width;
transition-duration: 2s;
transition-delay: .5s;
}
div:hover {
background: green;
width: 500px;
transition-delay:;
}
transition-delay需要定义在普通状态下的CSS中,因为移开鼠标后div立即恢复到普通状态,读取的是普通状态下的CSS属性。另外普通状态下的CSS属性会应用到hover状态下,导致鼠标悬浮的动画也延迟了0.5s,所以要在hover状态下将此属性定义为0。
可以看出,悬浮鼠标和移出鼠标都会执行动画是因为定义在div中的transition-property和transition-duration同样作用在了div:hover中,所以可以定义transition: none移除某一阶段的动画。比如:
div {
width: 300px;
height: 200px;
background-color: red;
transition-property: background-color, width;
transition-duration: 2s;
}
div:hover {
background: green;
width: 500px;
transition-property: none;
}
上面移除了悬浮鼠标的动画效果。
可见,定义在元素上的transition是可以作用于其伪类的,并在伪类状态下再度运行动画,那么animation是不是一样呢,比如:
div {
width: 300px;
height: 200px;
background-color: red;
-webkit-animation: test1 2s forwards;
}
@-webkit-keyframes test1 {
from {background-color: green;}
to {background-color: red;}
}
鼠标悬浮时是否会执行动画?还有,如果涉及到几个属性的变化时,属性1的动画设置为2s,属性2的动画设置为3s,使用transition能不能实现呢?
下一篇animation将会解释其不同的工作方式。