警告框 - 如何在浏览器缓存中保存 close(x)

Alert box - How to save close(x) in browser cache

这里我有一个简单的警告框:

/* 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) 然后隐藏元素。但是当我刷新页面时,再次显示警告框。

如何在浏览完网站之前记住关闭警告框的选择?

更新2:

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);
});

您在上次编辑时差一点就搞定了。使用 sessionStorage(或者 localStorage,如果你想让你的数据持久化)。不要直接使用 js 更改显示属性,而是使用 css class,如果用户之前没有关闭它,则将其删除。 为 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>