如何利用localStorage实现关闭弹窗后页面刷新不再显示?
如何让浏览器记住弹窗已关闭的状态?
是的,你需要用到localStorage来实现这个需求——它能在用户浏览器中持久存储简单的键值对数据,刚好适合记录「用户已关闭弹窗」这个状态,即使页面刷新或重新访问也能读取到这个标记。
具体实现步骤:
- 页面加载时判断是否弹出弹窗:在原本的弹窗触发逻辑中,先检查
localStorage里是否存在popupClosed标记。如果不存在(说明用户没关闭过弹窗,或是清除了浏览器存储),才执行延迟显示弹窗的逻辑;如果标记存在,直接跳过弹窗显示。 - 关闭弹窗时记录状态:用户点击关闭按钮时,除了隐藏弹窗,还要往
localStorage写入popupClosed标记,标记用户已关闭过该弹窗。
修改后的完整代码(重点替换script部分):
<!DOCTYPE html> <html lang="en"> <head> <!--====== Design by foolishdeveloper.com =====--> <title>Automatic Popup</title> <!--Google Fonts--> <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet"> <!--Stylesheets--> <style media="screen"> *, *:before, *:after{ padding: 0; margin: 0; box-sizing: border-box; } .popup{ background-color: #808080; z-index: 3; width: 80%; position: fixed; transform: translate(-50%,-50%); left: 50%; top: 50%; border-radius: 8px; font-family: "Poppins",sans-serif; display: none; text-align: center; overflow:auto; } .popup button{ display: block; position:absolute; top: 30px; right: 30px; margin: 0 0 0 auto; background-color: transparent; font-size: 20px; color: #ffffff; background: #e04039; border-radius: 100%; width: 40px; height: 40px; border: none; outline: none; cursor: pointer; } .popup h2{ margin-top: -20px; } .popup p{ font-size: 1px; text-align: justify; margin: 0px 0; line-height: 25px; } </style> </head> <body> <h1>tretertertrt</h1> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Expedita distinctio fugiat alias iure qui, commodi minima magni ullam aliquam dignissimos</p> <!-- 省略重复文本段落 --> <div class="popup"> <button id="close">×</button> <p> <iframe width="100%" height="750" src="https://www.youtube.com/embed/CeWlh0rEE-8" title="One Data Point That Will Change How You Do B2B Marketing" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </p> </div> <!--Script--> <script type="text/javascript"> window.addEventListener("load", function(){ // 检查localStorage中是否存在弹窗已关闭的标记 const hasClosedPopup = localStorage.getItem('popupClosed'); if (!hasClosedPopup) { setTimeout( function open(event){ document.querySelector(".popup").style.display = "block"; }, 2000 ) } }); document.querySelector("#close").addEventListener("click", function(){ document.querySelector(".popup").style.display = "none"; // 往localStorage写入标记,记录用户已关闭弹窗 localStorage.setItem('popupClosed', 'true'); }); </script> </body> </html>
可选扩展:
如果希望弹窗在一段时间后(比如7天)再次弹出,可以存储时间戳代替布尔值,加载时判断当前时间是否超过存储的时间戳:
// 关闭弹窗时存储当前时间+7天的时间戳 localStorage.setItem('popupClosedTime', Date.now() + 7*24*60*60*1000); // 页面加载时判断 const closedTime = localStorage.getItem('popupClosedTime'); if (!closedTime || Date.now() > Number(closedTime)) { // 显示弹窗 }
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

