ツール管理へ戻る

v1 のソース

<!DOCTYPE html>
<html lang="ja">
<head>
  <!-- 文字化けを防ぐため、文字コードをUTF-8に指定します -->
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>お菓子の袋詰め計算</title>

  <style>
    /* ===== 画面全体の見た目 ===== */
    * {
      box-sizing: border-box;
    }

    body {
      margin: 0;
      min-height: 100vh;
      font-family: "Hiragino Kaku Gothic ProN", "Hiragino Sans", "Yu Gothic UI", "Meiryo", sans-serif;
      background: linear-gradient(135deg, #fff4e0 0%, #ffe3ec 100%);
      color: #4a3b35;
      display: flex;
      justify-content: center;
      align-items: flex-start;
      padding: 40px 16px;
    }

    /* ===== 中央のカード ===== */
    .card {
      width: 100%;
      max-width: 520px;
      background: #ffffff;
      border-radius: 20px;
      box-shadow: 0 8px 24px rgba(200, 120, 100, 0.18);
      padding: 32px 36px;
    }

    /* ===== タイトルと説明 ===== */
    h1 {
      margin: 0 0 12px;
      font-size: 1.8rem;
      color: #e0607e;
      text-align: center;
    }

    .description {
      margin: 0 0 28px;
      line-height: 1.7;
      text-align: center;
      color: #6b5a52;
    }

    /* ===== 入力欄 ===== */
    .field {
      margin-bottom: 20px;
    }

    .field label {
      display: block;
      font-weight: bold;
      margin-bottom: 8px;
    }

    .input-row {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .input-row input {
      flex: 1;
      font-size: 1.2rem;
      padding: 10px 14px;
      border: 2px solid #f3c6a5;
      border-radius: 12px;
      outline: none;
      transition: border-color 0.2s;
    }

    .input-row input:focus {
      border-color: #e0607e;
    }

    /* 入力に問題がある欄を赤く表示します */
    .input-row input.is-error {
      border-color: #d93a3a;
      background: #fff5f5;
    }

    .unit {
      font-size: 1.1rem;
      min-width: 2em;
    }

    /* ===== ボタン ===== */
    .buttons {
      display: flex;
      gap: 12px;
      margin-top: 8px;
    }

    button {
      flex: 1;
      font-size: 1.05rem;
      font-weight: bold;
      padding: 12px;
      border: none;
      border-radius: 12px;
      cursor: pointer;
      transition: transform 0.1s, opacity 0.2s;
    }

    button:hover {
      opacity: 0.9;
    }

    button:active {
      transform: scale(0.97);
    }

    .btn-calc {
      background: #e0607e;
      color: #ffffff;
    }

    .btn-clear {
      background: #f2e8e1;
      color: #6b5a52;
    }

    /* ===== 結果表示エリア ===== */
    .result {
      margin-top: 28px;
      padding: 20px;
      border-radius: 16px;
      background: #fdf7f2;
      border: 2px dashed #f3c6a5;
      min-height: 90px;
      line-height: 1.7;
    }

    .result-placeholder {
      margin: 0;
      color: #a8968c;
      text-align: center;
    }

    .result-main {
      margin: 0 0 14px;
      font-size: 1.3rem;
      font-weight: bold;
      text-align: center;
      color: #c2456a;
    }

    .result-boxes {
      display: flex;
      gap: 12px;
    }

    .result-box {
      flex: 1;
      background: #ffffff;
      border-radius: 12px;
      padding: 12px;
      text-align: center;
    }

    .result-box .label {
      display: block;
      font-size: 0.9rem;
      color: #8a7870;
    }

    .result-box .value {
      display: block;
      font-size: 1.8rem;
      font-weight: bold;
      color: #4a3b35;
    }

    /* エラーのときの結果エリア */
    .result.is-error {
      background: #fff5f5;
      border-color: #f0a0a0;
    }

    .error-list {
      margin: 0;
      padding-left: 1.4em;
      color: #c0392b;
    }
  </style>
</head>
<body>

  <main class="card">
    <!-- 1. タイトル -->
    <h1>🍬 お菓子の袋詰め計算</h1>

    <!-- 2. ツールの説明 -->
    <p class="description">
      用意したお菓子の個数と、1袋に入れる個数を入力してください。<br>
      完成する袋の数と、余るお菓子の数を計算します。
    </p>

    <!-- 入力フォーム(Enterキーでも計算できます) -->
    <form id="candyForm" novalidate>
      <!-- 3. お菓子の個数の入力欄 -->
      <div class="field">
        <label for="totalInput">用意したお菓子の個数</label>
        <div class="input-row">
          <input type="text" id="totalInput" inputmode="numeric" autocomplete="off" placeholder="例:103">
          <span class="unit">個</span>
        </div>
      </div>

      <!-- 4. 1袋に入れる個数の入力欄 -->
      <div class="field">
        <label for="perBagInput">1袋に入れるお菓子の個数</label>
        <div class="input-row">
          <input type="text" id="perBagInput" inputmode="numeric" autocomplete="off" placeholder="例:10">
          <span class="unit">個</span>
        </div>
      </div>

      <div class="buttons">
        <!-- 5. 計算するボタン -->
        <button type="submit" class="btn-calc">計算する</button>
        <!-- 6. 入力をクリアするボタン -->
        <button type="button" class="btn-clear" id="clearButton">入力をクリアする</button>
      </div>
    </form>

    <!-- 7. 計算結果の表示場所(aria-liveで読み上げソフトにも結果を伝えます) -->
    <section class="result" id="resultArea" aria-live="polite">
      <p class="result-placeholder">ここに計算結果が表示されます</p>
    </section>
  </main>

  <script>
    // ===== 画面の部品を取得しておきます =====
    const form = document.getElementById("candyForm");
    const totalInput = document.getElementById("totalInput");
    const perBagInput = document.getElementById("perBagInput");
    const clearButton = document.getElementById("clearButton");
    const resultArea = document.getElementById("resultArea");

    // ----------------------------------------------------------
    // 全角数字や全角記号を半角に直す関数
    // (例:「103」→「103」)
    // ----------------------------------------------------------
    function toHalfWidth(text) {
      return text
        .replace(/[0-9]/g, function (ch) {
          return String.fromCharCode(ch.charCodeAt(0) - 0xFEE0);
        })
        .replace(/[.]/g, ".")
        .replace(/[-ー−]/g, "-");
    }

    // ----------------------------------------------------------
    // 入力確認の関数
    // 問題がなければ { ok: true, value: 数値 } を返します。
    // 問題があれば { ok: false, message: 案内文 } を返します。
    // ----------------------------------------------------------
    function validateInput(rawText, itemName) {
      // 前後の空白を取り除き、全角を半角に直します
      const text = toHalfWidth(rawText.trim());

      // 空欄のとき
      if (text === "") {
        return { ok: false, message: "「" + itemName + "」が空欄です。数字を入力してください。" };
      }

      // 数字の形になっていないとき(文字が混ざっているなど)
      if (!/^-?\d+(\.\d+)?$/.test(text)) {
        return { ok: false, message: "「" + itemName + "」には数字だけを入力してください。文字や記号は使えません。" };
      }

      // 小数のとき
      if (text.includes(".")) {
        return { ok: false, message: "「" + itemName + "」に小数は使えません。1、2、3…のような整数を入力してください。" };
      }

      const value = Number(text);

      // 0以下のとき
      if (value <= 0) {
        return { ok: false, message: "「" + itemName + "」には1以上の数を入力してください。" };
      }

      // 大きすぎて正しく計算できないとき
      if (!Number.isSafeInteger(value)) {
        return { ok: false, message: "「" + itemName + "」の数が大きすぎます。もう少し小さい数を入力してください。" };
      }

      return { ok: true, value: value };
    }

    // ----------------------------------------------------------
    // 計算の関数
    // 袋の数(商)と残りの数(余り)を求めます
    // ----------------------------------------------------------
    function calculatePacking(total, perBag) {
      const bags = Math.floor(total / perBag); // 割り算の商(小数点以下は切り捨て)
      const remainder = total % perBag;        // 割り算の余り
      return { bags: bags, remainder: remainder };
    }

    // ----------------------------------------------------------
    // 結果エリアの中身を空にする関数
    // ----------------------------------------------------------
    function resetResultArea() {
      resultArea.textContent = "";
      resultArea.classList.remove("is-error");
    }

    // ----------------------------------------------------------
    // 計算結果を表示する関数
    // 安全のため、文字は textContent で入れます(HTMLとして扱いません)
    // ----------------------------------------------------------
    function showResult(result) {
      resetResultArea();

      // まとめの一文
      const mainText = document.createElement("p");
      mainText.className = "result-main";
      mainText.textContent = result.bags + "袋完成し、" + result.remainder + "個残ります";
      resultArea.appendChild(mainText);

      // 袋の数と残りの数を、それぞれ箱で表示します
      const boxes = document.createElement("div");
      boxes.className = "result-boxes";
      boxes.appendChild(createResultBox("完成する袋の数", result.bags + " 袋"));
      boxes.appendChild(createResultBox("残るお菓子の数", result.remainder + " 個"));
      resultArea.appendChild(boxes);
    }

    // ----------------------------------------------------------
    // 結果の小さな箱(見出しと数字)を作る関数
    // ----------------------------------------------------------
    function createResultBox(labelText, valueText) {
      const box = document.createElement("div");
      box.className = "result-box";

      const label = document.createElement("span");
      label.className = "label";
      label.textContent = labelText;

      const value = document.createElement("span");
      value.className = "value";
      value.textContent = valueText;

      box.appendChild(label);
      box.appendChild(value);
      return box;
    }

    // ----------------------------------------------------------
    // 入力エラーの案内を表示する関数
    // ----------------------------------------------------------
    function showErrors(messages) {
      resetResultArea();
      resultArea.classList.add("is-error");

      const list = document.createElement("ul");
      list.className = "error-list";
      messages.forEach(function (message) {
        const item = document.createElement("li");
        item.textContent = message;
        list.appendChild(item);
      });
      resultArea.appendChild(list);
    }

    // ----------------------------------------------------------
    // 入力欄の赤い枠(エラー表示)を付けたり外したりする関数
    // ----------------------------------------------------------
    function markInput(inputElement, hasError) {
      if (hasError) {
        inputElement.classList.add("is-error");
        inputElement.setAttribute("aria-invalid", "true");
      } else {
        inputElement.classList.remove("is-error");
        inputElement.removeAttribute("aria-invalid");
      }
    }

    // ----------------------------------------------------------
    // 「計算する」ボタンが押されたときの関数
    // 入力確認 → 計算 → 結果表示 の順に進めます
    // ----------------------------------------------------------
    function handleCalculate(event) {
      // フォーム送信でページが再読み込みされないようにします
      event.preventDefault();

      const totalCheck = validateInput(totalInput.value, "お菓子の個数");
      const perBagCheck = validateInput(perBagInput.value, "1袋に入れる個数");

      markInput(totalInput, !totalCheck.ok);
      markInput(perBagInput, !perBagCheck.ok);

      // どちらかに問題があれば、計算せずに案内を出します
      const errors = [];
      if (!totalCheck.ok) errors.push(totalCheck.message);
      if (!perBagCheck.ok) errors.push(perBagCheck.message);

      if (errors.length > 0) {
        showErrors(errors);
        // 最初に問題がある欄へカーソルを移します
        (totalCheck.ok ? perBagInput : totalInput).focus();
        return;
      }

      const result = calculatePacking(totalCheck.value, perBagCheck.value);
      showResult(result);
    }

    // ----------------------------------------------------------
    // 「入力をクリアする」ボタンが押されたときの関数
    // ----------------------------------------------------------
    function clearInputs() {
      totalInput.value = "";
      perBagInput.value = "";
      markInput(totalInput, false);
      markInput(perBagInput, false);

      // 結果エリアを最初の案内文に戻します
      resetResultArea();
      const placeholder = document.createElement("p");
      placeholder.className = "result-placeholder";
      placeholder.textContent = "ここに計算結果が表示されます";
      resultArea.appendChild(placeholder);

      totalInput.focus();
    }

    // ===== ボタンと関数を結び付けます =====
    form.addEventListener("submit", handleCalculate);
    clearButton.addEventListener("click", clearInputs);
  </script>

</body>
</html>