我們用關鍵幀關鍵幀可以實現精靈圖的切換,同時通過background-size
背景解決了自適應的問題,這樣還是不夠的,元素還僅僅只是在原地進行幀動畫,要讓一個元素動起來必須要配合元素坐標的變化
因此在實現上,讓元素動起來:
運動 = 關鍵幀動畫 + 坐標變化
關鍵幀動畫我們已經實現了,那坐標的變化就很簡單了,一般來說前端能用到的手段
元素.position
定位,修改top
,left
坐標修改
通過css3
的transform
屬性的translate
無論用那種需要記住的是元素的坐標 都是 position+translate
的值的總和
transition
是css3
引入的"過渡"屬性,可以讓css
的屬性值在一定的時間區間內平滑地過渡,考慮兼容性問題,這里會額外引入一個插件jquery.transit,這個就是具體封裝了transition的CSS3過渡動畫的實現
接下來代碼部分就非常簡單了
transition的使用與jQuery提供的animate()方法基本差不多,所以使用上很容易接受,讓飛鳥執行一個飛的動作,可以這樣用
$(".bird").transition({ 'right': "3rem",},
10000,'linear',function(){ alert("結束")});
只要給出position
的坐標值,同時給出變化的時間就讓元素動起來了,結合一下精靈動畫,是不是看起來物體運動就是那么回事了?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>圣誕主題</title>
<style type="text/css">
.bird {
min-width: 4rem;
min-height: 2rem;
top: 10%;
right: 0;
position: absolute;
z-index: 10;
background: url(http://img.mukewang.com/55ade1700001b38302730071.png);
background-size: 300% 100%;
}
.birdFly {
/*寫法1*/
-moz-animation-name: bird-slow;
-moz-animation-duration: 400ms;
-moz-animation-timing-function: steps(1,start);
-moz-animation-iteration-count: infinite;
/*寫法2*/
-webkit-animation:bird-slow 400ms steps(3) infinite;
}
@-webkit-keyframes bird-slow {
0% {
background-position: -0% 0%;
}
100% {
background-position: -300% 0%;
}
}
@-moz-keyframes bird-slow {
0% {
background-position: -0% 0%;
}
50% {
background-position: -100% 0%;
}
75% {
background-position: -200% 0%;
}
100% {
background-position: -300% 0%;
}
}
</style>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script><script src="http://cdn.bootcss.com/jquery.transit/0.9.12/jquery.transit.min.js"></script>
</head>
<body>
<div class="bird birdFly"></div>
<button>點擊運動</button>
</body>
<script type="text/javascript">
$("button").on("click",function(){
/**
* 通過transition的方式改變運動
*/
$(".bird").transition({
'right': "3rem",
}, 10000,'linear',function(){
alert("結束")
});
})
var docEl = document.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function() {
//設置根字體大小
docEl.style.fontSize = 20 * (docEl.clientWidth / 320) + 'px';
};
//綁定瀏覽器縮放與加載時間
window.addEventListener(resizeEvt, recalc, false);
document.addEventListener('DOMContentLoaded', recalc, false);
</script>
</html>