在这里,我有一个简单的警报框:
/* The alert PROMO box */
.promobox {
padding: 10px;
background-color: #415ca2; /* Blue */
color: white;
margin-bottom: 7px;
}
/* The close button */
.closebtnpr {
margin-left: 15px;
color: white;
font-weight: bold;
float: right;
font-size: 18px;
line-height: 20px;
cursor: pointer;
transition: 0.3s;
}
/* When moving the mouse over the close button */
.closebtn:hover {
color: black;
}
<div class="promobox">
<span class="closebtnpr" onclick="this.parentElement.style.display='none';">×</span>
<center><b>U.S. POLO ASSN. DAY!</b></center>
</div>
当我单击(x)时隐藏元素。但是,当我刷新页面时,再次显示警报框。
如何记得在浏览完网站之前关闭警报框的选择?
update2:
sessionStorage.setItem('myCat', 'Tom');
下面的示例自动保存文本字段的内容,如果不小心刷新了浏览器,将恢复文本字段的内容,以免丢失任何文字。
// Get the text field that we're going to track
let field = document.getElementById("field");
// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if (sessionStorage.getItem("autosave")) {
// Restore the contents of the text field
field.value = sessionStorage.getItem("autosave");
}
// Listen for changes in the text field
field.addEventListener("change", function() {
// And save the results into the session storage object
sessionStorage.setItem("autosave", field.value);
});
答案 0 :(得分:1)
您几乎在上次编辑中得到了它。使用sessionStorage(如果希望数据持久化,则使用localStorage)。不要使用js直接更改display属性,而应使用css类,如果用户之前没有关闭过它,请将其删除。 为sessionStorage变量使用布尔值。
此代码段在沙盒环境中不起作用
document.addEventListener("DOMContentLoaded", function() {
let dismissed = sessionStorage.getItem("dismissed");
let alertDiv = document.getElementById("alert");
let dismissButton = document.getElementById("dismiss");
if(!dismissed){
alertDiv.classList.remove("hide");
}
addEventListener("click", function(){
alertDiv.classList.add("hide");
sessionStorage.setItem("dismissed", true);
});
});
.alert{border: 1px dashed lime; font-size: x-large; display: inline-block}
.hide{display: none}
<div class="alert hide" id="alert">
SOME ANNOYING ALERT HERE!
<button type="button" id="dismiss">X</button>
</div>