本篇文章不一一列舉CSS3動畫的屬性,若須要瞭解API,可前往 MDNcss
在開始栗子前,咱們先補補基礎知識。前端
css3 動畫分爲如下兩類:css3
animation: name duration timing-function delay iteration-count direction;web
ease 規定慢速開始,而後變快,而後慢速結束的過渡效果。bash
ease-in 規定以慢速開始的過渡效果。css3動畫
ease-out 規定以慢速結束的過渡效果。dom
ease-in-out 規定以慢速開始和結束的過渡效果。ide
linear 動畫從頭至尾的速度是相同的。函數
cubic-bezier(n,n,n,n) 在cubic-bezier函數中本身的值,n取值爲0~1學習
steps()
有些狀況咱們須要確保動畫結束後再進行另一些交互,可以使用該事件監聽。
slide.addEventListener("webkitAnimationEnd", function() {
console.log('eeee') //動畫結束再調用
});
複製代碼
假如咱們須要實現一個這樣簡單的動畫:
仔細觀察上面的動畫,咱們發現,它能夠由如下3部分組成:
入場動畫——從右往左移動
左右循環移動
逐幀動畫
使用3個dom元素,最外層dom實現入場動畫,第二層dom實現左右移動,第三層dom實現逐幀動畫。
入場動畫持續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;
}
複製代碼
使用下面這張雪碧圖,經過改變background-position實現動畫切換。
蹬蹬蹬,效果以下面所示,是否是很失望😞
緣由:因爲animation默認以ease方式過渡,它會在每一個關鍵幀之間插入補間動畫,因此動畫效果是連貫性的。此時可使用steps()取消補間動畫。
貼一個圖:
接着,咱們將timing-function改爲 step-end,效果以下:
animation: sprite 2s step-end .6s infinite both;
複製代碼
出現想要的效果了哈~不錯。
完整的css代碼以下: (能夠直接用下面的代碼加上面的圖片完成一個demo)
.anima_entrance {
position: absolute;
z-index: 3;
top: 5.1rem;
left: 4.05rem;
width: 12.9rem;
height: 19.1rem;
-webkit-animation: anima_entrance .6s ease-in-out both;
animation: anima_entrance .6s ease-in-out both;
}
.anima_move {
width: 218px;
height: 382px;
position: absolute;
z-index: 1;
top: 0;
left: 42px;
-webkit-animation: anima_move 2s linear .6s infinite both;
animation: anima_move 2s linear .6s infinite both;
}
.anima_sprite {
width: 218px;
height: 382px;
background: url(demo.png) no-repeat 0 0;
background-size: 25.8rem 19.1rem;
-webkit-animation: anima_sprite 2s step-end .6s infinite both;
animation: anima_sprite 2s step-end .6s infinite both;
}
@keyframes anima_entrance {
0% {
-webkit-transform: translate3d(18.75rem, 0, 0);
transform: translate3d(18.75rem, 0, 0);
}
100% {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
}
@keyframes anima_move {
0%, 16%, 42%, 74%, 100% {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
29% {
-webkit-transform: translate3d(-1rem, 0, 0);
transform: translate3d(-1rem, 0, 0);
}
87% {
-webkit-transform: translate3d(1rem, 0, 0);
transform: translate3d(1rem, 0, 0);
}
}
@keyframes anima_sprite {
0%, 16%, 42%, 58%, 74%, 100% {
background-position: -12.9rem 0;
}
8%, 50%, 66% {
background-position: 0 0;
}
}
複製代碼
一個複雜的動畫,經過梳理分層, 就能夠簡單的實現出來, 試着從新看看你的動畫把~
歡迎關注「前端加加」, 按期分享優質文章
回覆加羣,邀你進技術羣,長期技術交流學習