CSS Animation
2025年3月5日大约 3 分鐘
🎯 學習目標
- 了解 CSS 動畫(Animation) 的基本概念
- 學會使用
@keyframes
製作動畫 - 掌握
animation
相關屬性(duration
,timing-function
,iteration-count
等) - 學會
transition
讓動畫更順滑 - 實作練習
🔹CSS 動畫(Animation)是什麼?
CSS Animation 讓 HTML 元素可以 隨時間變化樣式,常用於:
- 按鈕 hover 動畫
- 圖片滑入滑出
- 淡入淡出效果
- 旋轉 & 移動動畫
- Loading 動畫
📌 CSS 動畫的主要技術
transition
(過渡效果) → 簡單動畫(如顏色、大小變化)@keyframes
(關鍵影格動畫) → 複雜的動畫效果
🔹transition
(過渡效果)
📌 transition
語法
transition: 屬性 時間 緩動方式 延遲時間;
📌 常見 transition
屬性
all
→ 所有屬性變化ease
→ 平滑開始 & 結束ease-in
→ 慢開始ease-out
→ 慢結束ease-in-out
→ 慢開始 & 慢結束linear
→ 均速變化
📌 當滑鼠移動到元素上時,讓它變大
.button {
background: blue;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
transition: all 0.3s ease;
}
.button:hover {
background: red;
transform: scale(1.1); /* 變大 */
}
🔹@keyframes
(關鍵影格動畫)
📌 animation
語法
animation: bounce 2s ease-in-out 1s infinite alternate;
📌 常見 animation
屬性
animation-name
→ 動畫名稱(對應@keyframes
)animation-duration
→ 動畫時間(2s
= 2 秒)animation-timing-function
→ 緩動方式(如ease-in-out
)animation-delay
→ 延遲時間(1s
= 1 秒後執行)animation-iteration-count
→ 執行次數(infinite
= 無限次)animation-direction
→ 動畫方向(alternate
= 來回播放)
📌 範例:讓元素左右移動
@keyframes moveRight {
0% { transform: translateX(0); }
100% { transform: translateX(200px); }
}
.box {
width: 100px;
height: 100px;
background: lightblue;
animation: moveRight 2s ease-in-out infinite alternate;
}
📝 CSS Animation 範例實作
📝 練習 1:製作跳動按鈕
📌 目標
- 讓按鈕持續彈跳
- 使用
@keyframes
來控制動畫
<style>
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-10px); }
}
.button {
background: orange;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
animation: bounce 0.5s infinite alternate;
}
</style>
<button class="button">跳動按鈕</button>
📝 練習 2:旋轉動畫
📌 目標
- 讓方塊無限旋轉
- 使用
@keyframes
讓它轉 360 度
<style>
@keyframes rotate {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.box {
width: 100px;
height: 100px;
background: lightgreen;
animation: rotate 2s linear infinite;
}
</style>
<div class="box"></div>
📝 練習 3:淡入淡出效果
📌 目標
- 讓文字慢慢出現
- 使用
opacity
來做漸變動畫
<style>
@keyframes fadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
.text {
font-size: 24px;
font-weight: bold;
animation: fadeIn 2s ease-in-out;
}
</style>
<div class="text">慢慢出現的文字</div>
📝 練習 4:按鈕 Hover 動畫
📌 目標
- 滑鼠移動到按鈕時,讓它變色並旋轉
<style>
.button {
background: blue;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
transition: all 0.3s ease-in-out;
}
.button:hover {
background: red;
transform: rotate(10deg) scale(1.1);
}
</style>
<button class="button">Hover 我</button>
🎯 CSS Animation 設計重點
✅ transition
→ 適用於簡單的 顏色、大小變化
✅ @keyframes
→ 適用於 複雜的動畫效果
✅ animation
→ 控制 動畫時間、次數、方向
✅ 搭配 transform
(旋轉、縮放)來增加動畫效果
📚 學習資源