商品を クリックすると 金額を 計算するよ。
お店屋さんごっこを しよう!
このレッスンの やりかた:
total = total + 100 のように、計算をさせるよ!商品ボタンと、合計金額を表示する場所を作ろう。
HTML の中に、下のコードを書いてね。
<div class="register-box">
<h2>プチタスーパー 🛒</h2>
<!-- 合計を表示する場所 -->
<div class="display">
合計: <span id="price">0</span> 円
</div>
<!-- 商品ボタン -->
<button onclick="addApple()" class="item-btn apple">🍎 りんご (100円)</button>
<button onclick="addOrange()" class="item-btn orange">🍊 みかん (50円)</button>
<hr> <!-- 線の区切り -->
<button onclick="reset()" class="reset-btn">お会計 (リセット)</button>
</div>
span タグは、文章の一部だけを つかまえるときに 便利だよ。
レジの画面っぽく デザインしよう。
CSS の中に 追加してね。
body {
text-align: center;
background-color: #f1f8e9;
font-family: sans-serif;
}
.register-box {
background-color: #fff;
width: 300px;
margin: 20px auto;
padding: 20px;
border: 5px solid #4caf50;
border-radius: 10px;
}
.display {
background-color: #333;
color: #00ff00; /* 電光掲示板っぽい色 */
font-size: 30px;
padding: 10px;
margin-bottom: 20px;
font-family: monospace;
}
.item-btn {
display: block;
width: 100%;
padding: 10px;
margin: 5px 0;
font-size: 18px;
cursor: pointer;
}
.apple { background-color: #ffcdd2; }
.orange { background-color: #ffe0b2; }
金額を保存する変数と、表示する場所を用意しよう。
JS の中に 書いてね。
// 合計金額の入れ物 (最初は 0)
let total = 0;
// 表示する場所をつかまえる
const monitor = document.getElementById("price");
total という変数ができたよ。「りんご」と「みかん」のボタンを押したときの 関数を作ろう。
さっきのコードの下に 続けて書いてね。
// りんご (100円) をたす
function addApple() {
total = total + 100;
monitor.innerHTML = total;
}
// みかん (50円) をたす
function addOrange() {
total = total + 50;
monitor.innerHTML = total;
}
さいごに、合計を 0 に戻す「リセット」を作るよ。
「ありがとうございました!」と アラートも 出してみよう。
// お会計 (リセット)
function reset() {
alert(total + "円 になります。まいどあり!");
total = 0;
monitor.innerHTML = total;
}
コードを改造して、自分だけのお店にしよう。
100 や 50 を変えて、値上げしちゃう?total = total - 100 で値引きする!