Element: animationstart 事件
當 CSS 動畫開始時,將觸發 animationstart 事件。如果存在 animation-delay,則在延遲期結束後會觸發此事件。負延遲將導致事件以等於延遲絕對值的 elapsedTime 觸發(相應地,動畫將在序列中的該時間索引開始播放)。
語法
在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。
js
addEventListener("animationstart", (event) => { })
onanimationstart = (event) => { }
事件型別
一個 AnimationEvent。繼承自 Event。
事件屬性
也繼承自其父級 Event 的屬性.
AnimationEvent.animationName只讀-
一個字串,包含生成動畫的
animation-name的值。 AnimationEvent.elapsedTime只讀-
一個
float,表示在觸發此事件時,動畫已執行的時間(以秒為單位),不包括動畫暫停的任何時間。對於animationstart事件,elapsedTime為0.0,除非animation-delay的值為負,在這種情況下,事件將以elapsedTime為(-1 * delay)觸發。 AnimationEvent.pseudoElement只讀-
一個字串,以
'::'開頭,包含動畫執行的 偽元素的名稱。如果動畫不在偽元素上執行,而是在元素上執行,則為空字串:''。
示例
監聽 animationstart 事件,並在其觸發時記錄一條訊息。
js
const animated = document.querySelector(".animated");
animated.addEventListener("animationstart", () => {
console.log("Animation started");
});
相同,但使用 onanimationstart。
js
const animated = document.querySelector(".animated");
animated.onanimationstart = () => {
console.log("Animation started");
};
即時示例
HTML
html
<div class="animation-example">
<div class="container">
<p class="animation">You chose a cold night to visit our planet.</p>
</div>
<button class="activate" type="button">Activate animation</button>
<div class="event-log"></div>
</div>
CSS
css
.container {
height: 3rem;
}
.event-log {
width: 25rem;
height: 2rem;
border: 1px solid black;
margin: 0.2rem;
padding: 0.2rem;
}
.animation.active {
animation-duration: 2s;
animation-name: slide-in;
animation-iteration-count: 2;
}
@keyframes slide-in {
from {
transform: translateX(100%) scaleX(3);
}
to {
transform: translateX(0) scaleX(1);
}
}
JavaScript
js
const animation = document.querySelector("p.animation");
const animationEventLog = document.querySelector(
".animation-example>.event-log",
);
const applyAnimation = document.querySelector(
".animation-example>button.activate",
);
let iterationCount = 0;
animation.addEventListener("animationstart", () => {
animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `;
});
animation.addEventListener("animationiteration", () => {
iterationCount++;
animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `;
});
animation.addEventListener("animationend", () => {
animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`;
animation.classList.remove("active");
applyAnimation.textContent = "Activate animation";
});
animation.addEventListener("animationcancel", () => {
animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`;
});
applyAnimation.addEventListener("click", () => {
animation.classList.toggle("active");
animationEventLog.textContent = "";
iterationCount = 0;
const active = animation.classList.contains("active");
applyAnimation.textContent = active
? "Cancel animation"
: "Activate animation";
});
結果
規範
| 規範 |
|---|
| CSS 動畫級別 1 # eventdef-globaleventhandlers-animationstart |
瀏覽器相容性
載入中…