You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

天气APP按时间切换发光颜色功能JavaScript问题求助

Fixes for Weather App Glow Effect

Let's break down the issues in your code and fix them step by step:


1. Fix the Hours Variable (Critical!)

Your code converts hours to a string with spaces (using padStart(2, "0 ")), which breaks numeric comparisons. We need to keep a numeric version of the hour for logic checks, and a formatted string only for display.

Corrected Code:

let now = new Date();
let currentDate = document.getElementById("date-element");

let date = now.getDate();
// Keep numeric hours for logic, formatted string for display
let hoursNum = now.getHours();
let hours = hoursNum.toString().padStart(2, "0"); // Use "0" to avoid spaces
let minutes = now.getMinutes().toString().padStart(2, "0");

// ... rest of your date formatting code remains the same
currentDate.innerHTML = `${day}, ${month} ${date},  ${hours}:${minutes}`;

2. Correct the Glow Function Logic

Your else condition has an impossible check (hours <6 && hours >=16 — no number can satisfy both). Also, you need to remove the opposite class before adding the correct one to avoid CSS conflicts.

Corrected Code:

function glow() {
  let app = document.getElementById("weather-app");
  // Reset: remove both classes first
  app.classList.remove("am", "pm");
  
  // 6:00 to 15:59 (before 16:00) = yellow glow (.am)
  if (hoursNum >= 6 && hoursNum < 16) {
    app.classList.add("am");
  } 
  // All other times = purple glow (.pm)
  else {
    app.classList.add("pm");
  }
}
glow();

3. Clean Up HTML Classes

Your HTML has both am and pm classes on the app container. Since CSS applies styles based on class order, the last class will always override the first — even if JS adds the other one. Remove both classes from the HTML so JS can control which one is active.

Corrected HTML:

<div class="container-lg mt-5 mb-2" id="weather-app">
  <!-- rest of your HTML content -->
</div>

Why This Works:

  • We use a numeric hoursNum variable for accurate time comparisons.
  • We reset the classes before adding the correct one, ensuring only the active glow style is applied.
  • We remove conflicting classes from the HTML, letting JS fully control the visual state.

内容的提问来源于stack exchange,提问作者Coding Newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 03:02:05