最近雜七雜八的事情不少,不少知識都沒來得及總結,是時候總結總結,開啓新的篇章~css
本篇文章不一一列舉CSS3動畫的屬性,若須要瞭解API,可前往 MDN css3
在開始栗子前,咱們先補補基礎知識。 web
css3動畫分類:css3動畫
animation經常使用屬性及場景:dom
animation: name duration timing-function delay iteration-count direction;
1. timing-function屬性: ide
ease 規定慢速開始,而後變快,而後慢速結束的過渡效果。函數
ease-in 規定以慢速開始的過渡效果。動畫
ease-out 規定以慢速結束的過渡效果。url
ease-in-out 規定以慢速開始和結束的過渡效果。spa
linear 動畫從頭至尾的速度是相同的。
cubic-bezier(n,n,n,n) 在cubic-bezier函數中本身的值,n取值爲0~1
動畫原則:
配合JS使用
slide.addEventListener("webkitAnimationEnd", function() { console.log('eeee') //動畫結束再調用 });
有些狀況咱們須要確保動畫結束後再進行另一些交互,可以使用該事件監聽。
實戰演習:
假如咱們須要實現一個這樣簡單的動畫:
仔細觀察上面的動畫,咱們發現,它能夠由如下3部分組成:
1. 入場動畫——從右往左移動
2. 左右循環移動
3. 逐幀動畫
實現方法:
使用3個dom元素,最外層dom實現入場動畫,第二層dom實現左右移動,第三層dom實現逐幀動畫。
優勢:調試方便,節省時間。
缺點:dom多。
1. dom結構
<div class="anima_entrance"> <div class="anima_move"> <div class="anima_sprite"></div> </div> </div>
2. 分析動畫造成的時間軸:
入場動畫持續0.6s,只播放一次,左右移動以及逐幀動畫持續2s,循環播放,代碼以下:
.anima_entrance { animation: anima_entrance .6s ease-in-out both; } .anima_move { animation: anima_move 2s linear .6s infinite both; } .anima_sprite { animation: anima_sprite 2s step-end .6s infinite both; }
接着,咱們將timing-function改爲 step-end,效果以下:
animation: sprite 2s step-end .6s infinite both;
出現想要的效果了哈~不錯。
完整的css代碼以下:
1 .anima_entrance { 2 position: absolute; 3 z-index: 3; 4 top: 5.1rem; 5 left: 4.05rem; 6 width: 12.9rem; 7 height: 19.1rem; 8 -webkit-animation: anima_entrance .6s ease-in-out both; 9 animation: anima_entrance .6s ease-in-out both; 10 } 11 12 .anima_move { 13 width: 218px; 14 height: 382px; 15 position: absolute; 16 z-index: 1; 17 top: 0; 18 left: 42px; 19 -webkit-animation: anima_move 2s linear .6s infinite both; 20 animation: anima_move 2s linear .6s infinite both; 21 } 22 23 .anima_sprite { 24 width: 218px; 25 height: 382px; 26 background: url(demo.png) no-repeat 0 0; 27 background-size: 25.8rem 19.1rem; 28 -webkit-animation: anima_sprite 2s step-end .6s infinite both; 29 animation: anima_sprite 2s step-end .6s infinite both; 30 } 31 32 @keyframes anima_entrance { 33 0% { 34 -webkit-transform: translate3d(18.75rem, 0, 0); 35 transform: translate3d(18.75rem, 0, 0); 36 } 37 100% { 38 -webkit-transform: translate3d(0, 0, 0); 39 transform: translate3d(0, 0, 0); 40 } 41 } 42 43 @keyframes anima_move { 44 0%, 16%, 42%, 74%, 100% { 45 -webkit-transform: translate3d(0, 0, 0); 46 transform: translate3d(0, 0, 0); 47 } 48 29% { 49 -webkit-transform: translate3d(-1rem, 0, 0); 50 transform: translate3d(-1rem, 0, 0); 51 } 52 87% { 53 -webkit-transform: translate3d(1rem, 0, 0); 54 transform: translate3d(1rem, 0, 0); 55 } 56 } 57 58 @keyframes anima_sprite { 59 0%, 16%, 42%, 58%, 74%, 100% { 60 background-position: -12.9rem 0; 61 } 62 8%, 50%, 66% { 63 background-position: 0 0; 64 } 65 }