「ダークモードと季節判定をJSで操作する」

今回は JavaScript を使って、時間によるダークモード判定と季節の背景色切り替えを実装します。

現在のモードに応じて背景色が変わります

季節はここに表示されます

<pre class="EnlighterJSRAW" data-enlighter-language="js">
// =======================================
// 🌙 背景色&季節判定プログラム
// =======================================


// =======================================
// 🚩 DOMContentLoaded
// =======================================
// - HTMLの構造が読み込まれたら実行されるイベント
// - 投稿ページにある <div> や <p> が確実に取得できる
// =======================================
// DOM が準備できたら実行
document.addEventListener("DOMContentLoaded", function() {

 // =======================================
  // 🚩STEP1: ダークモード判定
  // =======================================
  // 4️⃣ 関数を定義(timeを引数に取り、条件で"dark"/"light"を返す)
  function getDarkModeStatus(time) {
      return time > 20 ? "dark" : "light"; // ← 戻り値(関数の外に出す値)
  }

  // 1️⃣ 変数を呼び出す(mode を準備)
  // 2️⃣ new Date() で現在の時刻を取得し、.getHours() で「時」を取り出す
  const mode = getDarkModeStatus(new Date().getHours());
// 6️⃣ 戻り値 "dark" または "light" が mode に代入される

// 7️⃣ WordPress投稿ページにある .darkmode-box を取得
  const darkmodeBox = document.querySelector(".darkmode-box");
  if(darkmodeBox){
      // 投稿内のボックスの背景色と文字色を切り替え
      darkmodeBox.style.backgroundColor = mode === "dark" ? "#000" : "#fff";
      darkmodeBox.style.color = mode === "dark" ? "#fff" : "#000";
  }



// 8️⃣ 結果を出力(確認用)
  console.log((バッククォート)現在のモード: ${mode}(バッククォート));
  // 例: 21時なら "dark"、10時なら "light"


// =======================================
  // 🚩STEP2: 季節判定
  // =======================================
  // 4️⃣ 関数を定義(monthを引数に取り、条件で季節を返す)
  function getSeason(month) {
// 5️⃣ if判定(月の範囲ごとに季節を返す)
      if (month >= 3 && month <= 5) return "春";
      if (month >= 6 && month <= 8) return "夏";
      if (month >= 9 && month <= 11) return "秋";
      return "冬";
  }
// 1️⃣ 変数を呼び出す(currentMonth, season を準備)
  const currentMonth = new Date().getMonth() + 1;
// 2️⃣ getSeason(currentMonth) を呼び出し

  const season = getSeason(currentMonth);
// WordPress投稿ページにある #season-display を取得
  const seasonDisplay = document.getElementById("season-display");
  if(seasonDisplay){
      seasonDisplay.textContent = "現在の月は " + currentMonth + " 月なので、季節は " + season + " です!";
  }
// 7️⃣ season を利用して結果を出力(確認用)
console.log((バッククォート)現在の月は ${currentMonth} 月です(バッククォート));





});



// =======================================
// まとめ(記述順と実行順)
// =======================================
// 記述順: function → 変数 → if文
// 実行順: 
// 1️⃣ 変数呼び出し → 2️⃣ 値の取得 → 3️⃣ 関数呼び出し → 
// 4️⃣ 関数定義の処理開始 → 5️⃣ if判定 → 
// 6️⃣ 戻り値を変数に代入 → 7️⃣ 変数を利用して処理 → 8️⃣ 結果を出力
</pre>