HTMLElement: animationiteration イベント
animationiteration
イベントは、 CSS アニメーションの反復が1回分終了し、次の回が始まったときに発生します。このイベントは animationend
イベントと同時には発生せず、従って animation-iteration-count
が1のアニメーションでは発生しません。
バブリング | あり |
---|---|
キャンセル | 不可 |
インターフェイス | AnimationEvent |
イベントハンドラープロパティ | onanimationiteration (en-US) |
例
このコードは animationiteration
を使用して、アニメーションの反復が終了した回数を追跡します。
const animated = document.querySelector('.animated');
let iterationCount = 0;
animated.addEventListener('animationiteration', () => {
iterationCount++;
console.log(`アニメーション反復回数: ${iterationCount}`);
});
同様に、 onanimationiteration
イベントハンドラープロパティを使用するとこうなります。
const animated = document.querySelector('.animated');
let iterationCount = 0;
animated.onanimationiteration = () => {
iterationCount++;
console.log(`アニメーション反復回数: ${iterationCount}`);
};
ライブデモ
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 Level 1 | 草案 | 初回定義 |
ブラウザーの互換性
BCD tables only load in the browser
関連情報
- CSS アニメーション
- CSS アニメーションの使用
AnimationEvent
- 関連イベント:
animationstart
,animationend
,animationcancel
Document
を対象としたこのイベント:animationiteration
Window
を対象としたこのイベント:animationiteration