CSS3中有两种方式实现动画,transition和animation+@keyframe。html
二者的做用机制不同:transition定义在可能要进行动画的元素上,对某些CSS属性进行监听,一旦CSS改变则进行动画;animation定义在立刻要进行动画的元素上,一旦定义动画即进行。web
好比当鼠标悬浮的时候,某元素由红色改成绿色。使用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的代码量更少,简介直观。spa
div { width: 300px; height: 200px; background-color: red; transition: background-color 2s; } div:hover { background-color: green; }
其中transition可做为监听器,监听background-color的改变,一旦改变则以前的值做为初始状态,后来的值做为终止状态,进行整个过渡动画。code
使用animation先要定义各类时间段的状态,这里只须要定义开始时间和结束时间,这个定义放在@keyframes中,anmation再调用这个keyframes。htm
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能够应付一些更复杂的需求。blog
如下先从简单的开始,也就是transition。animation
transition的意思不是动画,而是过渡,从一个状态过渡到另外一个状态。这意味着这个动画的执行包含三个要素,初始状态、过渡、终止状态。简单的结构意味着简单的实现和受限制的功能。transiton只包含四个属性:it
首先用transition-property监听多个属性,代码以下:io
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: 0; }
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将会解释其不一样的工做方式。