強大的CSS動畫:Transition與Animation

本文總結CSS3中兩個用來做動畫的屬性,一個是transition,另一個是animation

差異比較

CSS3 差異
transition 在給定的持續時間內平滑地更改屬性值(從一個值到另一個值),也就是只需要指定開始與結束的參數,參數改變時就觸發動畫。
常用語鼠標事件(:hoveractive:focus:click)或鍵盤輸入時觸發
需要事件觸發,無法在網頁加載時自動發生。一次性,不能重複發生,除非一再觸發。
只能定義開始狀態和結束狀態,不能定義中間狀態。
animation 可以自行寫動畫開始、進行間、結束時各階段的變化,適合用來做較細微的動畫表現。需要明確的指定關鍵幀(@keyframe)的參數。
網頁加載時會直接執行,可以自行控制各階段動畫的變化

animationtransition最大的不同在於transition是當參數改變時觸發,而animation則是直接就執行,所有動畫效果需要明確的指定關鍵幀的參數。

CSS3 簡寫順序
transition property名稱timing-function特效
animation name名稱timing-function特效
iteration-count次數fill-mode填充模式

瀏覽器支持

transition寫法

.box {
  width: 100px;
  height: 100px;
  background-color: purple;
  transition: width 2s ease-in 2s;
}

.box:hover {
  width: 200px;
  height: 200px;
  background-color: red;
}

animation寫法

.box {
  width: 100px;
  height: 100px;
  border: 1px solid #ccc;
  animation: change 5s; /*8個屬性中至少要有名稱、時間*/
}

/*設定開始與結束狀態*/
/*from 就是0%,to 就是100%*/
@keyframes change {
  from {
    background-color: #4BC0C8;
  }
  to {
    background-color: #C779D0;
  }
}
.box {
  width: 100px;
  height: 100px;
  border: 1px solid #ccc;
  animation: change 5s; /*8個屬性中至少要有名稱、時間*/
}

/*設定開始與結束狀態*/
/*from 就是0%,to 就是100%*/
@keyframes change {
  0% {
    background-color: #4BC0C8;
  }
  20% {
    background-color: #C779D0;
  }
  60% {
    background-color: #FEAC5E;
  }
  80% {
    background-color: #185a9d;
  }
  100% {
    background-color: #4BC0C8;
  }
}
屬性
animation-name @keyframes後的名稱
animation-duration時間 time以秒計算,如3s initial預設值inherit繼承父層
animation-timing-function特效 linear等速、easeease-inease-outease-in-outstep-startstep-endsteps(int,start/end)cubic-bezier(n,n,n,n)可上官網取值使用
animation-delay 以秒計算,如2s
animation-iteration-count次數 number預設值爲1,因此填2時,動畫跑的次數爲1+2=3infinite無限循環
animation-direction方向 normalreverse反向、alternate先反後正
animation-fill-mode forwards使用關鍵幀最後的值backwards使用最開始的值both
animation-play-state播放狀態 pause暫停running爲預設值initial預設值、inherit繼承父層

Animation.css

官網下載:Animate.css

最後,給大家推薦一個前端學習進階內推交流羣685910553前端資料分享),不管你在地球哪個方位,
不管你參加工作幾年都歡迎你的入駐!(羣內會定期免費提供一些羣主收藏的免費學習書籍資料以及整理好的面試題和答案文檔!)

如果您對這個文章有任何異議,那麼請在文章評論處寫上你的評論。

如果您覺得這個文章有意思,那麼請分享並轉發,或者也可以關注一下表示您對我們文章的認可與鼓勵。

願大家都能在編程這條路,越走越遠。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章