CSSアニメーションの制御
animation transition classList animationend
CSSのアニメーション・トランジションをJavaScriptから制御します。クラスの付け外しが基本パターンです。
🔗 このページはバニラJS + CSSを使ったアニメーション制御の実装です。React / Framer Motion を使った実装は「切り替え演出」ページを参照してください。
デモ:transition(クラス切り替えでアニメーション)
クリック
クリックでクラスが切り替わりtransitionが発火
デモ:animation の開始・一時停止
⏸️
⏸️
コード例
js
/* CSS */
.box {
transition: transform 0.3s ease, background-color 0.3s;
}
.box.active {
transform: scale(1.2);
background-color: red;
}
@keyframes slide-in {
from { transform: translateX(-100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.box.animate {
animation: slide-in 0.5s ease forwards;
}
/* JavaScript */
const box = document.querySelector('.box');
// transition はクラス切り替えで発火
box.classList.add('active'); // トランジション開始
box.classList.remove('active'); // 逆方向に戻る
// animation の制御
box.classList.add('animate');
// 一時停止・再開
box.style.animationPlayState = 'paused';
box.style.animationPlayState = 'running';
// アニメーション完了後のコールバック
box.addEventListener('animationend', (e) => {
console.log('アニメーション名:', e.animationName);
box.classList.remove('animate');
});
// トランジション完了後
box.addEventListener('transitionend', (e) => {
console.log('プロパティ:', e.propertyName);
});比較:animation vs transition
| 観点 | animation(@keyframes) | transition |
|---|---|---|
| トリガー | クラス追加、自動(infinite) | プロパティの変化時のみ |
| 中間フレーム | ✅ 複雑な動きが可能 | ❌ 開始〜終了のみ |
| 繰り返し | ✅ infinite対応 | ❌ 一回のみ |
| 適した用途 | ローディング、複雑な演出 | ホバー効果、状態変化 |
NEWWeb Animations API(JavaScript で完全制御)
CSS不要でJavaScriptだけでアニメーションを定義・制御できるネイティブAPIです。CSSアニメーションより細かい制御が可能です。
js
const el = document.querySelector('.box');
// アニメーション定義
const anim = el.animate(
[
{ transform: 'translateX(0)', opacity: 1 },
{ transform: 'translateX(100px)', opacity: 0 },
],
{
duration: 500, // ms
easing: 'ease-out',
fill: 'forwards', // 終了後に状態を維持
iterations: 1, // Infinity で繰り返し
}
);
// 完了を await できる
await anim.finished;
console.log('アニメーション完了');
// 再生制御
anim.pause();
anim.play();
anim.reverse();
anim.cancel();
// 現在時刻を操作
anim.currentTime = 250; // 中間から再生🤖 AIプロンプトテンプレート
以下の要件を満たすTypeScript + Reactコンポーネントを作成してください。 - Web Animations API(element.animate())を使ったアニメーション制御のサンプルを示す - play/pause/reverse/cancelメソッドでアニメーションを制御する例を含める - アニメーションの再生速度(playbackRate)を変更するサンプルを含める - fillモードとイージング関数の設定例を示す - getAnimations()で要素のアニメーションを一覧取得・制御するサンプルを含める - コメントは日本語で記述する
⚠️ このプロンプトはあくまでたたき台です。AIの回答はモデルやバージョン、会話の文脈によって毎回異なります。意図通りに動かない場合は、条件を追記・修正してお使いください。