如何实现24小时自动切换的禁用标志及剩余时长动态展示
嘿,这个需求其实挺常见的,我来给你拆解一套前端就能搞定的简易方案,完全不用复杂的后端支持👇
核心思路与实现步骤
首先得纠正一个小误区:单纯用布尔标志是不够的——因为你需要知道24小时的隐藏期什么时候结束,所以得存储「过期时间戳」,而不是只存“是否隐藏”的状态。不过实现起来非常简单,用浏览器的localStorage就能搞定所有逻辑。
1. 点击禁用按钮的逻辑
当用户点击禁用按钮时,我们计算出24小时后的时间戳,把它存在localStorage里,然后立即隐藏应用:
// 给禁用按钮绑定点击事件 document.getElementById('disableBtn').addEventListener('click', () => { // 计算24小时后的时间戳(毫秒为单位) const twentyFourHoursLater = Date.now() + 24 * 60 * 60 * 1000; // 存入localStorage(转成字符串存储,因为localStorage只能存字符串) localStorage.setItem('appHideExpire', twentyFourHoursLater.toString()); // 立即执行隐藏应用的操作 hideApp(); }); // 封装隐藏应用的辅助函数 function hideApp() { document.getElementById('appContainer').style.display = 'none'; // 显示倒计时容器 document.getElementById('countdownContainer').style.display = 'block'; }
2. 页面加载时的状态判断
每次页面刷新或重新打开时,先读取存储的过期时间戳,和当前时间对比:
- 如果当前时间还没到过期时间:继续隐藏应用,启动倒计时
- 如果已过过期时间:显示应用,同时清除存储的过期时间(保持存储干净)
// 页面加载完成后执行判断 window.addEventListener('load', () => { const expireTimeStr = localStorage.getItem('appHideExpire'); const appContainer = document.getElementById('appContainer'); const countdownContainer = document.getElementById('countdownContainer'); if (expireTimeStr) { const expireTime = parseInt(expireTimeStr); const now = Date.now(); if (now < expireTime) { // 还在隐藏期,隐藏应用并启动倒计时 hideApp(); startCountdown(expireTime); } else { // 隐藏期已过,恢复显示并清除存储 appContainer.style.display = 'block'; countdownContainer.style.display = 'none'; localStorage.removeItem('appHideExpire'); } } else { // 没有存储记录,正常显示应用 appContainer.style.display = 'block'; countdownContainer.style.display = 'none'; } });
3. 剩余时长动态展示
用一个每秒执行的定时器,计算当前时间和过期时间的差值,转换成小时、分钟、秒的格式,实时更新DOM。当倒计时结束后,自动恢复应用显示:
function startCountdown(expireTime) { const countdownEl = document.getElementById('countdownText'); // 每秒更新一次倒计时 const timer = setInterval(() => { const now = Date.now(); const remaining = expireTime - now; if (remaining <= 0) { // 倒计时结束,清除定时器,恢复应用显示 clearInterval(timer); document.getElementById('appContainer').style.display = 'block'; document.getElementById('countdownContainer').style.display = 'none'; localStorage.removeItem('appHideExpire'); return; } // 把剩余毫秒数转换成时分秒 const hours = Math.floor(remaining / (1000 * 60 * 60)); const minutes = Math.floor((remaining % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((remaining % (1000 * 60)) / 1000); // 格式化显示为两位数字,更新DOM countdownEl.textContent = `应用将在 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')} 后恢复显示`; }, 1000); }
额外补充
- 关于布尔标志:如果非要用布尔值,可以和时间戳一起存储,但其实只存时间戳就足够判断状态——存在时间戳且未过期=隐藏,否则=显示,这样更简洁。
- 跨浏览器同步:如果需要用户在不同浏览器上都保持隐藏状态,那得配合后端数据库(绑定用户账号),但如果只是单浏览器的需求,
localStorage完全够用,是最轻量化的方案。 - 兼容性:
localStorage支持所有现代浏览器,甚至IE8及以上都能正常使用,不用担心兼容问题。
内容的提问来源于stack exchange,提问作者Ilia Tapia
相关产品推荐
相关产品推荐

