關(guān)鍵幀
在頁面中,想讓元素"動起來"可以通過切換圖片的方式,也是常說的逐幀動畫。常規(guī)的手段就是通過定時器不斷的切換圖片,配合時間,從而產(chǎn)生連續(xù)播放而成動畫。以前只能通利用JS器定時器或者flash達到這個逐幀播放的效果,現(xiàn)在可以通過CSS3的關(guān)鍵幀動畫,或者更為先進的“骨骼動畫”來實現(xiàn),效果也是極好的。
CSS3的Animation有八個屬性
animation-name :動畫名
animation-duration:時間
animation-delay:延時
animation-iteration-count:次數(shù)
animation-direction:方向
animation-play-state:控制
animation-fill-mode:狀態(tài)
animation-timing-function:關(guān)鍵幀變化
8個屬性中,其中1-7都有相關(guān)介紹,但是animation-timing-function是控制時間的屬性,在取值中除了常用到的 三次貝塞爾曲線 以外,還有個很高級的 steps()函數(shù)。
steps要配合精靈圖使用,簡單來說就是用來切換多個精靈圖的,形成幀動畫,類似setTimeout的處理感覺
動畫原理:
假如,現(xiàn)在有一組由三張圖合成的雪碧圖,每張圖大小是91*71

如果實現(xiàn)3張圖幀動畫效果,代碼如下
animation:bird-slow 400ms steps(3) infinite;
@keyframes
bird-slow {
0% {
background-position-x: -0px
}
100% {
background-position-x: -273px
}
}```
通過定義一個類,類中定義的動畫的一些關(guān)鍵數(shù)據(jù),比如動畫名,時間,次數(shù),切換的位置
通過`keyframes`定義動畫具體執(zhí)行參數(shù)與時間段
`steps(3)`的意思就是:`keyframes`設(shè)置的0%-100%的段中,`background-position`的的x坐標會變化3次
steps會**平分**這些段落值,其變化值就是
background-position-x: -0px
background-position-x: -91px
background-position-x: -182px
為什么沒有-273px,這個是steps的具體一個算法,參考博客 [深入理解CSS3 Animation 幀動畫](http://www.cnblogs.com/aaronjs/p/4642015.html)
下邊代碼給出了animation的2種寫法,一種是快捷寫法,一種是全寫,注意瀏覽器的兼容性需要加前綴
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>會飛的鳥</title>
<style type="text/css">
.bird {
min-width: 91px;
min-height: 71px;
top: 10%;
position: absolute;
z-index: 10;
background: url(http://img.mukewang.com/55ade1700001b38302730071.png);
}
.birdFly {
/*寫法1*/
-moz-animation: bird-slow 400ms steps(1,start) infinite;
-webkit-animation: bird-slow 400ms steps(1,start) infinite;
animation: bird-slow 400ms steps(1,start) infinite;
/*寫法2*/
-webkit-animation-name: bird-slow;
-webkit-animation-duration: 400ms;
-webkit-animation-timing-function: steps(3);
-webkit-animation-iteration-count: infinite;
}
@-webkit-keyframes bird-slow {
0% {
background-position: -0px 0px;
}
100% {
background-position: -273px 0px;
}
}
@-moz-keyframes bird-slow {
0% {
background-position: -0px 0px;
}
100% {
background-position: -273px 0px;
}
}
@keyframes bird-slow {
0% {
background-position: -0px 0px;
}
100% {
background-position: -273px 0px;
}
}
</style>
</head>
<body>
會飛的鳥
<div class="bird birdFly"></div>
</body>
<script type="text/javascript">
var docEl = document.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function() {
//設(shè)置根字體大小
docEl.style.fontSize = 20 * (docEl.clientWidth / 320) + 'px';
};
//綁定瀏覽器縮放與加載時間
window.addEventListener(resizeEvt, recalc, false);
document.addEventListener('DOMContentLoaded', recalc, false);
</script>
</html>