色変えボタンを作ろう

💻 この課題はPCで実際にコードを書いて取り組みましょう
1

HTMLファイルを作ろう

タイトルと色ボタンを並べるエリアを作りましょう。

💡 ヒント
index.html, style.css, script.js を作成し、HTMLからCSSとJSを読み込みます。
📝 模範解答を見る

⚠️ まず自分で考えてから見よう!

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>色変えボタン</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="app">
    <h1>🎨 色変えボタン</h1>
    <div class="buttons"></div>
  </div>
  <script src="script.js"></script>
</body>
</html>
2

色ボタンをHTMLに並べよう

5色以上のボタンを配置しましょう。各ボタンに data-color 属性で色コードを持たせます。

💡 ヒント
button 要素に style で background-color を指定し、data-color 属性に色コードを入れます。
📝 模範解答を見る

⚠️ まず自分で考えてから見よう!

<div class="buttons">
  <button class="btn" data-color="#ff6b6b" style="background:#ff6b6b;"></button>
  <button class="btn" data-color="#ffd93d" style="background:#ffd93d;"></button>
  <button class="btn" data-color="#6bcb77" style="background:#6bcb77;"></button>
  <button class="btn" data-color="#4d96ff" style="background:#4d96ff;"></button>
  <button class="btn" data-color="#c77dff" style="background:#c77dff;"></button>
</div>
3

クリックで背景色を変えよう

ボタンをクリックしたとき、そのボタンの色で背景色を変える処理を書きましょう。

💡 ヒント
querySelectorAll で全ボタンを取得し、forEach でクリックイベントを登録します。document.body.style.background で背景色を変更します。

参考: JS レッスン6: DOM操作

📝 模範解答を見る

⚠️ まず自分で考えてから見よう!

const buttons = document.querySelectorAll(".btn");
buttons.forEach(function(btn) {
  btn.addEventListener("click", function() {
    document.body.style.background = btn.dataset.color;
  });
});
4

CSSでボタンを丸くデザインしよう

ボタンを丸い形にし、影をつけてデザインしましょう。body に transition をつけると色の変化が滑らかになります。

💡 ヒント
border-radius: 50% で丸くし、box-shadow で影をつけます。
📝 模範解答を見る

⚠️ まず自分で考えてから見よう!

* { box-sizing: border-box; margin: 0; }
body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #f5f5f5; transition: background 0.3s; }
.app { text-align: center; }
h1 { font-size: 1.4rem; margin-bottom: 20px; color: #333; }
.buttons { display: flex; gap: 12px; flex-wrap: wrap; justify-content: center; }
.btn { width: 60px; height: 60px; border: 3px solid #fff; border-radius: 50%; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.15); }
5

動作確認して完成!

ブラウザで開いて、すべてのボタンが正しく動くか確認しましょう。

💡 ヒント
各ボタンをクリックして背景色が変わるか確認しましょう。transition で滑らかに変化すればOKです。
📝 模範解答を見る

⚠️ まず自分で考えてから見よう!

完成!各ボタンをクリックして背景色が滑らかに変われば成功です。

💡 アレンジアイデア:
・ランダムボタンを追加して、ランダムな色に変える
・テキストの色も一緒に変える
・色の名前を表示する
🎯

📚 使う技術を学ぶ

⚠️ つまずいたら