ボタンを ポチッ!
背景の 色が しゅんかんで 変わるよ。
このレッスンの やりかた:
style.backgroundColor を使って、色を操るよ!まずは、「あさ」「ゆうがた」「よる」の 3つのボタンを作ろう。
HTML の中に、下のコードを書いてね。
<div class="wrapper">
<!-- メッセージを表示する場所 -->
<h1 id="msg">おはよう!</h1>
<!-- 色を変える 3つのボタン -->
<div class="btn-area">
<button onclick="morning()">☀️ あさ</button>
<button onclick="evening()">🌇 ゆうがた</button>
<button onclick="night()">🌙 よる</button>
</div>
</div>
onclick="..." の名前が それぞれ 違うことに 注目!
ボタンを真ん中に寄せて、かっこよく デザインしよう。
CSS の中に 追加してね。
body {
text-align: center;
font-family: sans-serif;
/* ふわっと色がかわる魔法 (アニメーション) */
transition: background-color 0.5s, color 0.5s;
}
.wrapper {
margin-top: 100px;
}
button {
font-size: 20px;
padding: 10px 20px;
margin: 10px;
border: 2px solid white;
background-color: rgba(255,255,255,0.3);
border-radius: 30px;
cursor: pointer;
}
button:hover {
background-color: white;
}
transition (トランジション) というのが ポイント!まずは、「あさ」ボタンを押したときの morning 関数を作ろう。
JS の中に 書いてね。
// メッセージの場所をつかまえておく
const text = document.getElementById("msg");
// 「あさ」にする関数
function morning() {
// ① 背景を 水色にする
document.body.style.backgroundColor = "#81d4fa";
// ② 文字を 黒にする
document.body.style.color = "#333";
// ③ メッセージを変える
text.innerHTML = "おはよう!";
}
document.body は、画面全体のこと。style.backgroundColor で、背景色を書き換えられるんだ!
残りの 2つの関数も 作ろう!
色コード(#...)を変えるのが コツだよ。
// 「ゆうがた」にする関数
function evening() {
document.body.style.backgroundColor = "#ff9800"; /* オレンジ */
document.body.style.color = "#fff";
text.innerHTML = "さようなら!";
}
// 「よる」にする関数
function night() {
document.body.style.backgroundColor = "#1a237e"; /* 濃い紺色 */
document.body.style.color = "#fff"; /* 白文字 */
text.innerHTML = "おやすみなさい...";
}
好きな色のボタンを 増やしてみよう!
pink (ピンク) の「春(はる)」ボタンlimegreen (きみどり) の「森(もり)」ボタンblack (まっくろ) の「停電(ていでん)?!」ボタン