HTML5的動畫(Animation)是藉由CSS3新的定義屬性@keyframes,定義出動畫中每一個階段樣式的變化,再透過CSS的class設定動畫名稱、播放完成所需要的時間、線性、次數、方向;最後再透過Javascript來控制動畫開始的時機。
透過下列步驟立即體驗基本的動畫設計:
屬性@keyframes定義出動畫中每一個階段樣式的變化
<style>
@keyframes backgroundImg {
0% {
background-position: top;
background-size: 100% 100%;
background-image: url(Images/IMG_6272.JPG);
}
33% {
background-position: right;
background-size: 300px 200px;
background-image: url(Images/IMG_6275.JPG);
}
66% {
background-position: bottom;
background-size: 100% 100%;
background-image: url(Images/IMG_6276.JPG);
}
100% {
background-position: left;
background-size: 300px 200px;
background-image: url(Images/IMG_6277.JPG);
}
}
</style>
上列的定義background-image可以四階段展現四張圖片,透過定義background-position可以改變圖片的位置,透過background-size可以讓動畫出現單張到重覆多格圖片的動畫效果,當然還能夠繼續添加其他樣式設計,就能達到千變萬化的效果。
CSS的class設定動畫名稱、播放完成所需要的時間、線性、方向、次數
.animate {
animation-name: backgroundImg;
animation-duration: 5s;
animation-timing-function: linear;
/*normal:單向, reverse:反向,alternate:來回,alternate-reverse:反向來回*/
animation-direction: normal;
animation-iteration-count: 3;
}
透過Javascript來控制動畫開始的時機
<style>
#bg {
width: 800px;
height: 600px;
background-image: url(Images/IMG_6272.JPG);
background-size: 100% 100%;
}
</style>
<div id="bg" title="Click Me!!"></div>
<script>
document.getElementById("bg").addEventListener("click", function (e) {
this.classList.add("animate");
});
document.getElementById("bg").addEventListener("animationend", function () {
this.classList.remove("animate");
});
</script>
透過基本的樣式設計,讓div顯示圖片IMG_6272.JPG,註冊圖片被點選的事件,套用動畫設定的類別.animate,註冊動畫結束的事件,移除套用過的動畫設定類別。透過調整這些定義就能玩出更特別的動畫囉!
您可在下列課程中了解更多技巧喔!
相關學習資源
【HTML5】HTML5與CSS3網站開發實務