CSS3 動畫能讓網頁以更輕量的方式呈現動態效果。以下以照片長廊為例,示範如何只用 CSS3 完成背景漸層、容器移動、關鍵幀動畫與圖片放大效果。
先替頁面加上由上而下的漸層背景,讓畫面更有層次。
background: -webkit-gradient(linear, 0 0, 0 100%, from(#F9F9F9), to(#5F5F5F));
建立一個寬度足夠的容器,並設定動畫名稱、時間、循環次數與方向。
.player {
width:1500px;
position:absolute;
left:0px;
top:0px;
-webkit-animation-name: goleft;
-webkit-animation-duration: 15s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-direction: alternate;
}透過 keyframes 定義容器移動的路徑,讓照片長廊依序移動。
@-webkit-keyframes goleft {
from { left: 0; }
25% { left: -300px; }
50% { left: -600px; }
75% { left: -900px; }
to { left: -1200px; }
}當滑鼠移到圖片上時,可觸發另一組動畫,讓圖片平滑放大。
.player a:hover img {
-webkit-animation-name: zoomIn;
-webkit-animation-duration: 5s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-direction: alternate;
}
@-webkit-keyframes zoomIn {
from { -webkit-transform: scale(1); }
25% { -webkit-transform: scale(1.2); }
50% { -webkit-transform: scale(1.4); }
to { -webkit-transform: scale(1.6); }
}若搭配 HTML5 音訊標籤,還能加入背景音樂。再透過 CSS3 動畫製作假的音頻均衡器,讓畫面更有趣味性。
#mBar span:nth-child(1) {
-webkit-animation-name: bar;
-webkit-animation-duration: 3s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-direction: alternate;
background: -webkit-gradient(linear, 0 0, 0 100%, from(#FF00CC), to(#E8E8E8));
}整體而言,這個範例展示了 CSS3 動畫在視覺呈現上的可能性。即使不用 JavaScript,也能做出流暢、有趣的照片長廊。