ボタンクリックアニメーション
CoddyのHTMLジャーニー「JavaScriptの実践」セクションの一部。レッスン 20/27。
ボタンがクリックされたときに、小さくなったり、光ったり、弾んだりするような即時のフィードバックを返したいことがあります。JavaScriptを使ってCSSアニメーションやトランジションを発生させることができます。
まず、HTMLにシンプルなボタンを作成しましょう。
<button id="animatedButton">Click Me</button>次に、ボタンのスタイルを設定する基本的なCSSを追加します。
#animatedButton {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: transform 0.2s, background-color 0.2s;
}次に、クリックアニメーションを作成するためのJavaScriptを追加しましょう。
const button = document.getElementById('animatedButton');
button.addEventListener('click', function() {
// クリック時のエフェクト用のクラスを追加する
button.classList.add('button-clicked');
// アニメーションの完了後にクラスを削除する
setTimeout(function() {
button.classList.remove('button-clicked');
}, 200);
});最後に、アニメーション効果のCSSを追加します。セレクターはidとクラスを組み合わせているため、#animatedButtonルールより詳細度が高く、クラスが付いている間はそのbackground-colorが適用されます。
#animatedButton.button-clicked {
transform: scale(0.95);
background-color: #45a049;
}クリックすると、ボタンが少し縮んで色が変わり、ユーザーに視覚的なフィードバックを提供します。
チャレンジ
簡単ボタンがクリックされたら、視覚的なフィードバックとして CSS クラス "button-clicked" をボタンに追加します。
このクラスを適用する行を、クリックイベントリスナーの中に追加します。
自分で試してみよう
<!DOCTYPE html>
<html>
<head>
<title>Button Animation Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Interactive Button Demo</h1>
<p>Click the button below to see a smooth animation effect.</p>
</header>
<main class="content">
<button id="animatedButton" class="btn">Click Me</button>
</main>
<script src="script.js"></script>
</body>
</html>
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
JavaScriptの実践のすべてのレッスン
自分で練習してみよう: Webプレイグラウンド