首先給個地址查看下效果:
animate.css的主頁簡單明瞭,能演示各個動畫的效果,目的也很簡單,“just-add-water css animations”。
不多說,直接上學習資料:
使用方法:(當然你得引入animate.css)
一、靜態使用
給需要動畫的元素添加class
<!-- animated是必須添加的;bounce是動畫效果;infinite從語義來看也秒懂,無限循環,不添加infinite默認播放一次 -->
<div class="animated bounce infinite">動畫</div>
然後刷新之後就可以看到效果了
二、動態使用
思路:
給動畫對象添加類,然後監聽動畫結束事件,一旦監聽到動畫結束,立馬移除前面添加的類。
這樣一來,想什麼時候開始和結束動畫都隨你了。對於這種用法(也是實際開發中最多的用法),官方給出了jQuery的封裝:
//擴展$對象,添加方法animateCss
$.fn.extend({
animateCss: function (animationName) {
var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
$(this).addClass('animated ' + animationName).one(animationEnd, function() {
$(this).removeClass('animated ' + animationName);
});
}
});
//使用示例:
$('#yourElement').animateCss('bounce');
原生js寫法:
//animate("選擇器","動畫","次數","時延")
function animate(seletor, animation_name, count, delay) {
var target = document.querySelectorAll(seletor)
var timer = null;
timer = setInterval( function() {
target.forEach( function(x) {
x.className += " animated " + animation_name;
x.addEventListener("animationend", function(){
x.className = x.className.replace(" animated " + animation_name, "");
});
} )
count --;
if( count <= 0 ) {
clearInterval( timer );
}
}, delay)
}
//使用示例
animate('.haha', "bounce", 2, 1000);
源碼解析:
一,animated
設置了動畫時長和動畫執行前後元素應該怎樣應用樣式(animation-fill-mode)
animated {
-webkit-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
二,infinite
設置了動畫次數(無限次)
infinite {
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
}
三,動畫類名(如:bounce)
設置使用的動畫,及一些動畫的初始化屬性。
.bounce {
-webkit-animation-name: bounce;
animation-name: bounce;
-webkit-transform-origin: center bottom;
transform-origin: center bottom;
}
@keyframes bounce {
from, 20%, 53%, 80%, to {
-webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
40%, 43% {
-webkit-animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
-webkit-transform: translate3d(0, -30px, 0);
transform: translate3d(0, -30px, 0);
}
70% {
-webkit-animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
-webkit-transform: translate3d(0, -15px, 0);
transform: translate3d(0, -15px, 0);
}
90% {
-webkit-transform: translate3d(0,-4px,0);
transform: translate3d(0,-4px,0);
}
}
自定義選項
這個放在最後是因爲看了源碼之後很自然就無師自通懂得怎麼自定義了,例如想用css來控制動畫次數等。
#yourElement {
-vendor-animation-duration: 3s;
-vendor-animation-delay: 2s;
-vendor-animation-iteration-count: infinite;
}
記住:vendor要替換成相應的適配規格(-webkit-、-ms-、-o-等)