如何实现类似Cookie同意提示的顶部通知仅在首次访问/会话展示一次
实现方案
我们可以使用浏览器自带的sessionStorage存储通知关闭状态,它仅在当前浏览器会话(同一个标签页从打开到关闭的整个周期)内有效,完全匹配你需要的类似Cookie同意弹窗的展示逻辑。
你只需要把原有代码替换为下面的完整代码即可:
1. HTML代码
<div id="topNotificationBar"> <span class = "topDIV">Welcome to <em>Vitrify</em>. Following in the finest traditions of vitreous enamelled jewellery. <a href = "#">Find out more.</a></span> <button class = "button-x" onclick="myFunction()"></button> </div>
2. JS代码
// 页面加载时自动判断是否需要显示通知 window.onload = function() { if(sessionStorage.getItem('notificationClosed') === 'true') { document.getElementById('topNotificationBar').style.display = 'none'; } } // 点击关闭按钮的逻辑 function myFunction() { var notifyBar = document.getElementById("topNotificationBar"); notifyBar.style.display = "none"; // 存储关闭标记,当前会话内不再显示 sessionStorage.setItem('notificationClosed', 'true'); }
3. CSS代码
#topNotificationBar { width: 100%; box-sizing: border-box; padding: 10px 20px; background: #ff7f00; /* 此处可替换为你需要的顶部栏背景色 */ } .topDIV { color: #000000; font-weight: 300; font-size: 15px; } .topDIV a:link, .topDIV a:visited { color: #000000!important; font-weight: 500; letter-spacing: -0.3px; line-height: 1.2; } .topDIV a:hover { border-bottom: 1px solid rgba(0,0,0,0.50) !important; display: inline-block; } .button-x { position: relative; float: right; top: -5px; background:none; border:none; color:rgb(0,0,0) ; cursor: pointer; vertical-align: 0px; } .button-x:before { font-family: 'Times'; content: "X"; font-size:30px; vertical-align:0px; opacity:0.5; } .button-x:hover { opacity:1!important; }
实现效果
用户点击关闭通知后,只要不关闭当前站点的标签页,无论怎么刷新、跳转站内页面,通知都不会再次出现;用户关闭浏览器后重新访问站点,通知会再次展示一次。
内容的提问来源于stack exchange,提问作者Ricando
相关产品推荐
相关产品推荐

