animationstart
イベントは、 CSS アニメーションが開始したときに発生します。 animation-delay
がある場合、このイベントは待ち時間が経過したときに一度発生します。待ち時間が負の数の場合、イベントは elapsedTime
が待ち時間の絶対値と等しくなったときに発生します (および、関連して、アニメーションはシーケンスの中でそのタイムインデックスに再生が始まります)。
バブリング | あり |
---|---|
キャンセル | 不可 |
インターフェイス | AnimationEvent |
イベントハンドラープロパティ | onanimationstart |
例
このコードは animationstart
イベントを待ち受けし、イベント発生時にメッセージを記録します。
const animated = document.querySelector('.animated');
animated.addEventListener('animationstart', () => {
console.log('アニメーション開始');
});
同様に、 onanimationstart
を使用するとこうなります。
const animated = document.querySelector('.animated');
animated.onanimationstart = () => {
console.log('アニメーション開始');
};
ライブデモ
HTML
<div class="animation-example">
<div class="container">
<p class="animation">あなたは私たちの惑星を訪れるために寒い夜を選びました。</p>
</div>
<button class="activate" type="button">アニメーションを有効にする</button>
<div class="event-log"></div>
</div>
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: slidein;
animation-iteration-count: 2;
}
@keyframes slidein {
from {
transform: translateX(100%) scaleX(3);
}
to {
transform: translateX(0) scaleX(1);
}
}
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.addEventListener('animationiteration', () => {
iterationCount++;
animationEventLog.textContent = `${animationEventLog.textContent}'アニメーション反復: ${iterationCount}' `;
});
animation.addEventListener('animationend', () => {
animationEventLog.textContent = `${animationEventLog.textContent}'アニメーション終了'`;
animation.classList.remove('active');
applyAnimation.textContent = "アニメーションを有効にする";
});
animation.addEventListener('animationcancel', () => {
animationEventLog.textContent = `${animationEventLog.textContent}'アニメーション取り消し'`;
});
applyAnimation.addEventListener('click', () => {
animation.classList.toggle('active');
animationEventLog.textContent = '';
iterationCount = 0;
let active = animation.classList.contains('active');
if (active) {
applyAnimation.textContent = "アニメーションを取り消す";
} else {
applyAnimation.textContent = "アニメーションを有効にする";
}
});
結果
仕様書
仕様書 | 状態 | 備考 |
---|---|---|
CSS Animations | 草案 | 初回定義 |
ブラウザーの互換性
BCD tables only load in the browser
このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 https://github.com/mdn/browser-compat-data をチェックアウトしてプルリクエストを送信してください。
関連情報
- CSS アニメーション
- CSS アニメーションの使用
AnimationEvent
- 関連イベント:
animationend
,animationiteration
,animationcancel
Document
を対象としたこのイベント:animationstart
Window
を対象としたこのイベント:animationstart