本文介绍如何根据当前时间段(如早、中、晚)自动加载并显示不同的 html 页面,涵盖页面切换逻辑、异步内容获取、dom 替换及实际部署注意事项。
本文介绍如何根据当前时间段(如早、中、晚)自动加载并显示不同的 html 页面,涵盖页面切换逻辑、异步内容获取、dom 替换及实际部署注意事项。
在 Web 开发中,有时需要根据一天中的不同时段(例如早餐时段 7:00–11:59、午餐时段 12:00–16:59、晚餐时段 17:00–23:59)动态展示对应主题的 HTML 页面(如 breakfast.html、lunch.html、dinner.html)。这比单纯切换图片更复杂,需安全加载外部 HTML 内容,并完整替换当前页面结构(包括标题、样式、脚本和交互元素)。
以下是一个健壮、可维护、符合现代 Web 标准的实现方案:
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <title>时段专属菜单</title> <script> // 步骤 1:定义各时段对应的 HTML 页面路径 const timeBasedPages = { breakfast: '/html/breakfast.html', // 06:00 – 11:59 lunch: '/html/lunch.html', // 12:00 – 16:59 dinner: '/html/dinner.html', // 17:00 – 23:59 night: '/html/night.html' // 00:00 – 05:59 }; // 步骤 2:根据当前时间返回应加载的 URL function getCurrentPageUrl() { const hour = new Date().getHours(); if (hour >= 6 && hour < 12) return timeBasedPages.breakfast; if (hour >= 12 && hour < 17) return timeBasedPages.lunch; if (hour >= 17 && hour < 24) return timeBasedPages.dinner; return timeBasedPages.night; // 0–5 点 } // 步骤 3:异步加载并解析 HTML async function loadHtmlPage(url) { try { const response = await fetch(url); if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`); const htmlText = await response.text(); const parser = new DOMParser(); return parser.parseFromString(htmlText, 'text/html'); } catch (err) { console.error('页面加载失败:', err); throw err; } } // 步骤 4:安全替换当前页面内容 function replaceDocumentContent(newDoc) { // 更新页面标题 document.title = newDoc.title || '时段菜单'; // 清空 body 并注入新内容(保留当前 <head> 中的全局样式/脚本) document.body.innerHTML = newDoc.body.innerHTML; // ⚠️ 注意:若新页面含内联脚本(<script>),默认不会执行。 // 如需执行,请手动遍历并 append(见下方“进阶提示”) executeInlineScripts(newDoc.body); } // 辅助函数:执行新页面中所有内联 script 标签(可选) function executeInlineScripts(node) { const scripts = node.querySelectorAll('script'); scripts.forEach(script => { if (!script.src) { // 仅处理内联脚本 const newScript = document.createElement('script'); newScript.textContent = script.textContent; document.head.appendChild(newScript); } }); } // ✅ 启动:页面加载完成后立即执行 document.addEventListener('DOMContentLoaded', async () => { try { const url = getCurrentPageUrl(); const doc = await loadHtmlPage(url); replaceDocumentContent(doc); } catch (err) { document.body.innerHTML = `<h2>⚠️ 页面加载失败</h2><p>请检查网络或联系管理员。</p>`; } }); </script></head><body> <!-- 初始占位内容(加载期间显示) --> <div style="text-align:center; margin-top:2rem;"> <p>正在为您匹配今日时段菜单...</p> <div class="spinner"></div> </div></body></html>
fetch(url, { cache: 'no-store' })
该方案以语义清晰、分层解耦的方式实现了「按时间加载 HTML 页面」的核心需求:从时间判断 → 动态 URL 选择 → 安全内容获取 → DOM 注入 → 脚本补救,每一步都兼顾兼容性、安全性与可维护性。无论是单页菜单还是含交互的多图页面(如您提到的 HTML2.html 中可点击切换的三张图片),均可无缝支持——因为整个 <body> 已被完整替换,原有事件监听器与逻辑自然生效。
只需将 timeBasedPages 对象中的路径指向您的真实 HTML 文件,并确保服务器正确托管这些资源,即可开箱即用。
立即学习“前端免费学习笔记(深入)”;
阿里云百炼Token Plan和Coding Plan省钱订阅计划:如何选择?有哪些区别?
最新:阿里云万小智收费价格:活动15元1个月:180元1年:轻量版、标准版及高级版功能支持
移动端的AI助手不应只是客服窗口:更应借助AI能力将小程序服务变成可调用能力
AI搜索引用到客户咨询:中间隔着三层数据漏斗
【码道代码智能体】码道界面焕新:AI 懂需求 开发更顺手
CodexBar:把 AI 编码额度接入 macOS 菜单栏