CSS 3 動畫- animation

CSS3 Animations

css 3 的動畫在網頁上執行起來很順,現在我在做動畫也都會以 css3 的 animation 為主,要互動的話再加上 js 就好了,基本用法是用一個 @keyframes 開始,這邊用法跟 function 很像,要替 keyframes 取一個名字如下:

@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}

最簡單的就是 from 到 to,{}內就是要改變的 css 屬性,只要是可以漸變的屬性套進去,css就會把他變成動畫了。

除了 from 到 to 外,還可以設定 %,這樣動畫就會有更多變化,如:
@keyframes example {
  0% {background-color: red;}
  50% {background-color: yellow;}
  100% {background-color: blue;}
}

接下來我們要再選擇器上指定要使用這個動畫,最基本的就是指定動畫的名稱跟時間
animation: example 2s;

實際執行結果

See the Pen
css animation
by deathhell (@deathhell)
on CodePen.



比較完整的設定有這些屬性
animation-duration:
動畫執行時間,單位可為 s(秒),這樣動畫就會根據你設定的時間在每個百分比的階段變化



animation-delay:
延遲時間,以 s 為單位

animation-iteration-count:
播放次數,可為數字或是 infinite(無限播放)

animation-direction: 播放方向,有以下參數可以設定
normal: 從 0%播到100%
reverse: 從 100%播到0%
alternate: 播放兩次以上,奇數次從0%到100%,偶數次從100%到0%
alternate-reverse: 跟 alternate 相反


animation-fill-mode:
當動畫停止時顯示的狀態
forwards: 停在最後的狀態
backwards: 停在最初的狀態
both: 視 animation-direction 決定狀態


animation-timing-function:
時間函數,預設為 ease,如果設為 linear 則從頭到尾變化一樣,可以使用的值有
linear|ease|ease-in|ease-out|ease-in-out|step-start|step-end|steps(int,start|end)|cubic-bezier(n,n,n,n)
其中 steps 可以用來作 sprite 動畫
而 cubic-bezier 可以用來自動時間函式,由於數字太抽象,我們可以使用產生器幫我們調整時間函式並產出

animation-play-state:
動畫執行狀態,使用 paused 就會暫停,running 則為執行動畫


可以分開設定,也可以併在一起像這樣:
animation: name 5s linear 2s infinite alternate;

其中除了時間第一個是執行時間,第二個是 delay 時間外,其他的值沒有順序問題。

也可以一次執行很多個動畫如下:
name 5s linear, name2 5s ease

留言