最近一個小游戲項目用到了CSS3的動畫屬性,例如transition、transform、animation。經過三個星期,終於做完了,利用周末好好梳理總結一下。
Internet Explorer 10、Firefox 以及 Opera 支持 @keyframes 規則和 animation 屬性。
Chrome 和 Safari 需要前綴 -webkit-。

animation: name duration timing-function delay iteration-count direction;
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>delay</title>
<meta name="vIEwport" content="width=device-width, initial-scale=1" />
<style type="text/CSS">
@-webkit-keyframes delay{
99%{
-webkit-transform:translate(100px,0);
}
}
.delay{
width:100px;height:100px;
background-color: #000;
-webkit-animation:delay 1s linear 2s infinite;
animation:delay 1s linear 2s infinite;
}
</style>
</head>
<body>
<div class="delay"></div>
</body>
</Html>
animation-fill-mode
該屬性有四個值
none:默認值。不設置對象動畫之外的狀態
forwards:設置對象狀態為動畫結束時的狀態
backwards:設置對象狀態為動畫開始時的狀態
both:設置對象狀態為動畫結束或開始的狀態
一開始比較糾結著三個到底有什麼區別。網上也找了,發現網上說的有點錯誤。起碼我試了一下forwards和both的效果是一模一樣的。都是動畫運行完了停在哪裡就是哪裡。至於backwards,就是總停在一開始的狀態。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>delay</title>
<meta name="vIEwport" content="width=device-width, initial-scale=1" />
<style type="text/CSS">
@-webkit-keyframes delay{
100%{
-webkit-transform:translate(100px,0);
}
}
.delay{
width:100px;height:100px;
background-color: #000;
-webkit-animation:delay 1s linear 2 forwards alternate;
}
</style>
</head>
<body>
<div class="delay"></div>
</body>
</Html><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>delay</title>
<meta name="vIEwport" content="width=device-width, initial-scale=1" />
<style type="text/CSS">
@-webkit-keyframes delay{
100%{
-webkit-transform:translate(100px,0);
}
}
.delay{
width:100px;height:100px;
background-color: #000;
-webkit-animation:delay 1s linear 2 both alternate;
}
</style>
</head>
<body>
<div class="delay"></div>
</body>
</Html>
兩段代碼主要說明在forwards和both的情況下動畫在設置了反向運行偶次數時,效果仍然一樣。因為之前看到網上說的是forwards在偶次數反向是會停在關鍵幀的100%處,而不是0%處。
<!DOCTYPE HTML>
<Html>
<head>
<meta charset="utf-8">
<title>delay</title>
<meta name="vIEwport" content="width=device-width, initial-scale=1" />
<style type="text/CSS">
@-webkit-keyframes delay{
100%{
-webkit-transform:translate(100px,0);
}
}
.delay{
width:100px;height:100px;
background-color: #000;
-webkit-animation:delay 1s linear 2 both alternate;
}
</style>
</head>
<body>
<div class="delay"></div>
<script type="text/Javascript">
window.onload = function(){
var delay = document.getElementsByClassName("delay")[0],
time1,
time2;
delay.addEventListener("webkitAnimationStart",function(){
time1 = new Date().getTime();
time2 = time1;
console.log(time2-time1+"ms")
})
delay.addEventListener("webkitAnimationIteration",function(){
time2 = new Date().getTime();
console.log(time2-time1+"ms")
})
delay.addEventListener("webkitAnimationEnd",function(){
time2 = new Date().getTime();
console.log(time2-time1+"ms")
})
}
</script>
</body>
</Html>
從代碼可以看出,iteration是在動畫重復執行的時候觸發的。