某天看到 Google 首頁出現了幾個活潑的動畫,發現並非用 Flash 製作,而是純粹以 JS 加圖片實作!於是把素材收集起來,用 JavaScript 重現了這段動畫效果。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>谷歌首頁動畫</title>
<style type="text/css">
.animate{
height:156px;
width:97px;
background:url(images/gumby11-gumby.jpg) no-repeat;
background-position:-15581px center;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var offset = -15678;
$('#start').click(function(){
var timer = setInterval(function(){
offset += 98;
$('#animate').css({
'background-position': offset + 'px center'
});
if (offset > 0) {
clearInterval(timer);
}
}, 50);
$(this).hide();
});
});
</script>
</head>
<body>
<div id="animate" class="animate"></div>
<a id="start" href="javascript:void(0)">動起來吧!</a>
</body>
</html>
原理其實不難:把一長條「序列圖(sprite)」當作背景,透過 setInterval 每隔 50 毫秒把 background-position 往左推移一格(每格 98px),營造出連續播放的動畫感;當偏移超過 0 時清除計時器停止。真正考驗功力的,反而是那張序列圖素材本身該怎麼製作。