如何修复Splash Screen关闭标签页后不显示问题?求编写对应JS代码
修复启动页关闭标签页后重新显示的问题
注意:你的HTML代码中
content1的h1标签未正确闭合,建议修正为:<h1 class="splash-content" id="content1">Sub</h1>
下面提供三种针对性的解决方案,按需选择:
方案1:改用SessionStorage(推荐)
SessionStorage的特性是标签页关闭后数据自动清除,完美匹配“关闭页面后重新打开显示启动页”的需求,无需额外监听事件。
替换后的完整JS代码:
const splash = document.querySelector('.splash'); document.addEventListener('DOMContentLoaded', (e) => { setTimeout(() => { splash.classList.add('display-none'); }, 6000); }) var firstContainer = document.querySelector(".splash"); // 替换localStorage为sessionStorage var result = sessionStorage.getItem('hasRan'); if (!result) { sessionStorage.setItem('hasRan', true); } else { firstContainer.classList.remove("animated"); firstContainer.classList.add("post_animated"); }
方案2:监听页面关闭事件清除LocalStorage
如果需要保留LocalStorage的跨标签页特性,但希望关闭页面后重置状态,可以监听beforeunload事件,在页面关闭时删除存储的标记:
修改后的完整JS代码:
const splash = document.querySelector('.splash'); document.addEventListener('DOMContentLoaded', (e) => { setTimeout(() => { splash.classList.add('display-none'); }, 6000); }) var firstContainer = document.querySelector(".splash"); var result = localStorage.getItem('hasRan'); if (!result) { localStorage.setItem('hasRan', true); } else { firstContainer.classList.remove("animated"); firstContainer.classList.add("post_animated"); } // 页面关闭/刷新时清除标记 window.addEventListener('beforeunload', () => { localStorage.removeItem('hasRan'); });
方案3:设置时间限制(可选)
如果希望用户在指定时间内(比如24小时)只看到一次启动页,可以存储上次显示的时间戳,每次加载时判断是否超过限制:
修改后的完整JS代码:
const splash = document.querySelector('.splash'); document.addEventListener('DOMContentLoaded', (e) => { setTimeout(() => { splash.classList.add('display-none'); }, 6000); }) var firstContainer = document.querySelector(".splash"); const lastShownTime = localStorage.getItem('lastSplashShown'); const now = Date.now(); // 设置时间限制为24小时(单位:毫秒) const timeLimit = 24 * 60 * 60 * 1000; if (!lastShownTime || now - parseInt(lastShownTime) > timeLimit) { localStorage.setItem('lastSplashShown', now.toString()); } else { firstContainer.classList.remove("animated"); firstContainer.classList.add("post_animated"); }
方案说明
- 方案1:最简洁,完全满足“关闭标签页后重新打开显示启动页”的核心需求;
- 方案2:适合需要跨标签页共享“已看过启动页”状态,但关闭所有标签页后重置的场景;
- 方案3:适合希望控制用户重复看到启动页频率的场景,可自行调整
timeLimit的值修改时间间隔。
内容的提问来源于stack exchange,提问作者user22026776
相关产品推荐
相关产品推荐

