判断维护时段需将时间转为分钟数比较,注意时区统一;跨日时段要拆分为“当前≥起点”或“当前≤终点”两个条件。

用 JavaScript 判断当前时间是否在维护时段内
核心思路是获取 new Date() 的小时和分钟,与预设的维护开始/结束时间对比。注意时区——浏览器使用本地时区,若需统一按服务器时间(如 UTC+8),得手动校正或后端传参,否则用户在不同时区看到的“维护状态”可能不一致。
常见错误是直接比对字符串(如 "02:00" > "23:59"),结果不可靠;必须转成可比较的数值(如分钟数):
const now = new Date();
const currentMinutes = now.getHours() * 60 + now.getMinutes();
const startMinutes = 2 * 60 + 0; // 02:00 → 120 分钟
const endMinutes = 5 * 60 + 30; // 05:30 → 330 分钟
const isInMaintenance = currentMinutes >= startMinutes && currentMinutes <h3>维护公告 DOM 的显示与隐藏控制</h3><p>维护区域通常是一个全屏遮罩层(<code><div id="maintenance-banner">),初始应设为 <code>display: none</code> 或 <code>visibility: hidden</code>。JS 判断为维护时段后,再通过 <code>element.style.display = "block"</code> 激活。<p>容易踩的坑:</p>
<ul>
<li>没加 <code>DOMContentLoaded</code> 或 <code>window.onload</code> 就执行判断,导致 DOM 元素还不存在,<code>getElementById</code> 返回 <code>null</code>
</li>
<li>用 <code>visibility: hidden</code> 而非 <code>display: none</code>,虽隐藏但仍占布局空间,可能压住关键按钮或表单</li>
<li>未考虑移动端 viewport,遮罩层没设 <code>position: fixed</code> 和 <code>z-index</code>,导致滚动后公告错位或被盖住</li>
</ul>
<h3>支持跨天维护(如 23:00 至次日 06:00)的时间逻辑</h3>
<p>当维护时段跨越午夜(即 <code>startMinutes > endMinutes</code>),常规的「大于等于起点且小于等于终点」会失效。此时要拆成两个条件判断:</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill5806" title="html-deploy"><img
src="https://img.php.cn/upload/skill/000/000/081/179066538882434.jpg" alt="html-deploy" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill5806" title="html-deploy" class="overflowclass">html-deploy</a>
<p class="overflowclass">使用 htmlcode.fun 将 HTML 内容或文件部署到网页,适用于用户要求“部署到网页”“托管此 HTML”“生成此前端...的实时链接”等场景。</p>
</div>
<a rel="nofollow" href="/xiazai/skill5806" title="html-deploy" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<pre class="brush:php;toolbar:false;">const isInMaintenance =
(currentMinutes >= startMinutes) ||
(currentMinutes <p>例如:23:00(1380 分钟)到 06:00(360 分钟),只要当前分钟数 ≥1380(当天后半夜)或 ≤360(次日凌晨),即属维护中。这个逻辑不能省略,否则凌晨 01:00 就不会触发公告。</p><h3>避免页面加载完成前闪现正常内容</h3><p>用户网速快时,HTML 渲染早于 JS 执行,可能先看到首页,再突然弹出维护页——体验割裂。解决方法是在 <code></code> 中内联一段极简脚本,立即检查并隐藏主体内容:</p><pre class="brush:php;toolbar:false;"><script>
const now = new Date();
const h = now.getHours(), m = now.getMinutes();
const inRange = (h === 2 && m >= 0) || (h > 2 && h < 5) || (h === 5 && m <= 30);
if (inRange) {
document.documentElement.classList.add('in-maintenance');
}
</script>再配合 CSS:.in-maintenance main { display: none; }、.in-maintenance #maintenance-banner { display: block; }。这样样式层就先于 JS 完整逻辑接管,消除闪烁。
真正难处理的是缓存问题:用户上次访问时不在维护期,CDN 或浏览器缓存了旧 HTML,JS 一跑才发现已进维护,但页面结构已渲染完毕。这时候只能靠 Service Worker 拦截请求,或后端根据时间动态输出 HTML ——纯前端方案对此无能为力。










