CSS3,我們可以創建動畫,它可以取代許多網頁動畫圖像,Flash 動畫,和 Javascripts。
## CSS3 @keyframes 規則
要創建CSS3動畫,你將不得不了解`@keyframes`規則。
`@keyframes`規則是用來創建動畫。 `@keyframes`規則內指定一個 CSS樣式和動畫將逐步從目前的樣式更改為新的樣式。
**注意:**Internet Explorer 10、Firefox 以及 Opera 支持 `@keyframes` 規則和 animation 屬性。Chrome 和 Safari 需要前綴 -webkit-。
## CSS3 動畫
當在`@keyframe`創建動畫,把它綁定到一個選擇器,否則動畫不會有任何效果。
指定至少這兩個 CSS3 的動畫屬性綁定向一個選擇器:
- 規定動畫的名稱
- 規定動畫的時長
例子:
~~~
#animated_div {
animation: animated_div 5s infinite;
-moz-animation: animated_div 5s infinite;
-webkit-animation: animated_div 5s infinite;
}
~~~
## CSS3動畫是什么?
- 動畫是使元素從一種樣式逐漸變化為另一種樣式的效果。
- 您可以改變任意多的樣式任意多的次數。
- 請用百分比來規定變化發生的時間,或用關鍵詞 "from" 和 "to",等同于 0% 和 100%。
- 0% 是動畫的開始,100% 是動畫的完成。
- 為了得到最佳的瀏覽器支持,您應該始終定義 0% 和 100% 選擇器。
例子:
~~~
@keyframes animated_div {
0% {
left: 0px;
}
20% {
left: 50px;
background-color: green;
}
40% {
left: 140px;
background-color: red;
}
60% {
left: 280px;
background-color: yellow;
}
80% {
left: 425px;
background-color: blue;
}
100% {
left: 0px;
background-color: pink;
}
}
~~~
## 常用屬性
| 屬性 | 描述 | CSS |
|-----|-----|-----|
| [@keyframes](# "CSS3 @keyframes 規則") | 規定動畫。 | 3 |
| [animation](# "CSS3 animation 屬性") | 所有動畫屬性的簡寫屬性,除了 animation-play-state 屬性。 | 3 |
| [animation-name](# "CSS3 animation-name 屬性") | 規定 @keyframes 動畫的名稱。 | 3 |
| [animation-duration](# "CSS3 animation-duration 屬性") | 規定動畫完成一個周期所花費的秒或毫秒。默認是 0。 | 3 |
| [animation-timing-function](# "CSS3 animation-timing-function 屬性") | 規定動畫的速度曲線。默認是 "ease"。 | 3 |
| [animation-delay](# "CSS3 animation-delay 屬性") | 規定動畫何時開始。默認是 0。 | 3 |
| [animation-iteration-count](# "CSS3 animation-iteration-count 屬性") | 規定動畫被播放的次數。默認是 1。 | 3 |
| [animation-direction](# "CSS3 animation-direction 屬性") | 規定動畫是否在下一周期逆向地播放。默認是 "normal"。 | 3 |
| [animation-play-state](# "CSS3 animation-play-state 屬性") | 規定動畫是否正在運行或暫停。默認是 "running"。 | 3 |
## 源碼
本文中所用例子源碼參見[https://github.com/waylau/css3-tutorial](https://github.com/waylau/css3-tutorial) 中 `samples` 目錄下的 animation.html、animation_2.html