如何保存Modal状态并在指定时间后恢复显示?
实现关闭Modal后12小时自动恢复显示的方案
需求说明
首页加载多个Modal,当用户误关闭modal#2时,希望12小时后再次打开页面时,从该位置重新显示对应的Modal,使用localStorage实现(相比cookie更简单,无需额外处理过期配置,直接通过时间戳判断)。
具体实现步骤
- 记录关闭操作:监听所有Modal的关闭按钮,当用户点击关闭时,把当前Modal的ID和关闭时间存入localStorage。
- 页面初始化校验:页面加载完成后,读取存储的关闭记录,计算当前时间与关闭时间的差值,若超过12小时则自动打开对应的Modal,未超过则按原流程从modal#1启动。
- 正常流程清记录:当用户通过按钮(如Start、Next)主动切换Modal时,清除localStorage中的关闭记录,避免干扰正常流程。
修改后的完整代码
JavaScript 代码
// 打开Modal的基础函数 const openModal1 = () => { window.location.href = "#openModal1"; } const openModal2 = () => { window.location.href = "#openModal2"; } const openModal3 = () => { window.location.href = "#openModal3"; } // 监听所有Modal的关闭操作 document.addEventListener('click', (e) => { if (e.target.getAttribute('href') === '#close') { const modal = e.target.closest('.modalDialog'); if (modal) { // 存储关闭的Modal ID和时间戳 localStorage.setItem('closedModal', JSON.stringify({ id: modal.id, closeTime: Date.now() })); } } }); // 页面加载时校验是否需要恢复Modal window.addEventListener('load', () => { const closedRecord = localStorage.getItem('closedModal'); const TWELVE_HOURS = 12 * 60 * 60 * 1000; // 12小时对应的毫秒数 if (closedRecord) { const { id, closeTime } = JSON.parse(closedRecord); // 判断是否超过12小时 if (Date.now() - closeTime > TWELVE_HOURS) { window.location.href = `#${id}`; localStorage.removeItem('closedModal'); // 清除过期记录 } else { window.location.href = "#openModal1"; } } else { window.location.href = "#openModal1"; } }); // 正常切换Modal时清除关闭记录 function start() { localStorage.removeItem('closedModal'); openModal2(); } const btn_next = () => { localStorage.removeItem('closedModal'); openModal3(); }
HTML 代码
<div id="openModal1" class="modalDialog" data-modalorder="1"> <div> <a href="#close" title="Close">X</a> <h1>Content modal 1</h1> <input type="button" onclick="start()" value="Start"> </div> </div> <div id="openModal2" class="modalDialog" data-modalorder="2"> <div> <a href="#close" title="Close">X</a> <h1>Content modal 2</h1> <input type="button" onclick="btn_next()" value="Next"> </div> </div> <div id="openModal3" class="modalDialog" data-modalorder="3"> <div> <a href="#close" title="Close">X</a> <h1>Content modal 3</h1> <input type="button" onclick="" value="Next"> </div> </div>
CSS 代码
.modalDialog { position: fixed; font-family: 'Poppins', sans-serif; top: 0; right: 0; bottom: 0; left: 0; background: rgba(0, 0, 0, 0.8); z-index: 99999; opacity: 0; -webkit-transition: opacity 400ms ease-in; -moz-transition: opacity 400ms ease-in; transition: opacity 400ms ease-in; pointer-events: none; } .modalDialog:target { opacity: 1; pointer-events: auto; } .modalDialog>div { width: 500px; position: relative; margin: 10% auto; padding: 26px; border-radius: 2em; background: #fff; }
代码说明
- 采用
localStorage存储关闭记录,依赖时间戳判断是否超过12小时,无需手动配置过期规则。 - 通过事件委托监听所有关闭按钮,确保新增Modal时无需额外修改监听逻辑。
- 主动切换Modal时清除记录,避免正常流程被误关闭的记录干扰。
内容的提问来源于stack exchange,提问作者Coc L
相关产品推荐
相关产品推荐

