Menu
Coddy logo textTech

ボタンクリックアニメーション

CoddyのHTMLジャーニー「JavaScriptの実践」セクションの一部。レッスン 20/27。

クリックされたときに、縮んだり、光ったり、跳ねたりするなど、ボタンからすぐにフィードバックを返したい場合があります。JavaScriptを使ってCSSアニメーションやトランジションをトリガーできます。

まず、HTMLでシンプルなボタンを作成します。

<button id="animatedButton">Click Me</button>

次に、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() {
  // Add a class for the click effect
  button.classList.add('button-clicked');
  
  // Remove the class after animation completes
  setTimeout(function() {
    button.classList.remove('button-clicked');
  }, 200);
});

最後に、animation effect 用の CSS を追加します:

.button-clicked {
  transform: scale(0.95);
  background-color: #45a049;
}

button が clicked されると、button は少し縮小して color が変わり、ユーザーに視覚的なフィードバックを提供します。

challenge icon

チャレンジ

簡単

ボタンがクリックされたとき、視覚的なフィードバックのために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>
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

JavaScriptの実践のすべてのレッスン

自分で練習してみよう: Webプレイグラウンド