CSS語法 - Animation(動畫)

紀錄 CSS Animation的使用方法。

@keyframes

在@keyframes 規則內指定CSS樣式。
0% 表示起始,100% 表示結束。

以下執行後就會花5秒的時間,往右移動到 200px 的位置,再移動回 0px 的位置停止。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
.box1 {
position: absolute;
left: 0;
width: 50px;
height: 50px;
background-color: red;
animation-name: mov;
animation-duration: 5s;
}

@keyframes mov{
0% {
left: 0px;
}
50%{
left: 200px;
}
100%{
left: 0px;
}
}

animation-name

動畫名稱。(必要)

animation-duration

動畫持續時間,單位為 秒 ( s ) 或毫秒 ( ms )。(必要)

animation-iteration-count

動畫播放次數,預設值為 1 次,infinite 值為無窮重複。

animation-delay

動畫延遲播放時間,單位為 秒 ( s ) 或毫秒 ( ms )。
若將延遲播放時間設定為「負值」,則是快轉(例如 -2s,會直接從第二秒的位置開始播放)

animation-timing-function

加速度函式。值有:

  • ease: 慢-快-慢(預設值)。還有 ease-in、ease-out、ease-in-out
  • linear: 線性。

animation-direction

播放方向。值有:

  • normal: 正常播放(預設值)。
  • reverse: 反轉。
  • alternate: 正-反輪播。
  • alternate-reverse: 反-正輪播。

animation-fill-mode

播放結束後的模式。值有:

  • none: 返回原始狀態(預設值)。
  • forwards: 保持在結束的狀態。
  • backwards: 保持在開始的狀態。
  • both

animation-play-state

播放或暫停動畫。值有:

  • running: 運行(預設值)。
  • paused: 暫停。

Animation Events

可以使用 JavaScript 來接收動畫所產生的事件。

  • animationstart: 當動畫開始。
  • animationend: 當動畫結束。
  • animationiteration: 當動畫重複播放。

CSSKeyframesRule

可以使用 JavaScript 來修改動畫內容。

document.styleSheets : 包含了頁面中所有的外部樣式表的陣列。
cssRules : 存在於 styleSheets 中的屬性,可用來新增、刪除或編輯己存在的樣式規則。
而取得 cssRules 內的CSSKeyframesRule,就能夠修改動畫內容。

支援的方法:

  • findRule(): 尋找。
  • appendRule(): 添加。
  • deleteRule(): 刪除。

以下為點擊按鈕後會更換動畫的內容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<div class="box1"></div>
<button id="btn">更換</button>

<style>
.box1 {
position: absolute;
left: 0;
top: 50px;
width: 50px;
height: 50px;
background-color: red;
animation-name: mov;
animation-duration: 5s;
animation-iteration-count: 5;
}

@keyframes mov {
0% {
left: 0px;
}

50% {
left: 200px;
}

100% {
left: 0px;
}
}
</style>

<script>
var btn = document.getElementById('btn');
var keyframes = document.styleSheets[0].cssRules[1];
console.log(keyframes);

btn.addEventListener('click', function () {
console.log(keyframes.findRule('50%'));

keyframes.appendRule('50% {left:300px; background:blue;}');
// 向右移300px,背景色轉為藍色
});
</script>

參考資料 :
oxxostudio

作者

LeeU

發表於

2020-12-18

更新於

2024-04-04

許可協議