我有简单的警报框代码。仅单击(x)后应隐藏元素。
iusse::问题是我可以单击网站上的任意位置,然后该元素会自动隐藏。我希望仅单击(x)时隐藏该元素。
document.addEventListener("DOMContentLoaded", function() {
let dismissed = sessionStorage.getItem("dismissed");
let alertDiv = document.getElementById("promo");
let dismissButton = document.getElementById("dismiss");
if(!dismissed){
alertDiv.classList.remove("hide");
}
addEventListener("click", function(){
alertDiv.classList.add("hide");
sessionStorage.setItem("dismissed", true);
});
});
/* The alert PROMO box */
.promo {
padding: 10px;
background-color: #415ca2; /* Blue */
color: white;
margin-bottom: 7px;
}
.hide {
display: none;
}
/* 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 */
.closebtnpr:hover {
color: black;
}
<div class="promo hide" id="promo">
<span class="closebtnpr" id="dismiss">x</span>
<center>
<b>U.S. POLO ASSN. DAY!</b><br />
</center>
</div>
更新:
document.addEventListener("DOMContentLoaded", function() {
let dismissed = sessionStorage.getItem("dismissed");
let alertDiv = document.getElementById("promo");
let dismissButton.addEventListener("click", function(){
alertDiv.classList.add("hide");
sessionStorage.setItem("dismissed", true);
});
});
答案 0 :(得分:2)
let dismissed = sessionStorage.getItem("dismissed");
let dismissButton = document.getElementById("dismiss");
let alertDiv = document.getElementById("promo");
if(!dismissed){
alertDiv.classList.remove("hide");
}
dismissButton.addEventListener("click", function(){
alertDiv.classList.add("hide");
sessionStorage.setItem("dismissed", true);
});
您正在存储会话变量,因此在单击该框后,直到该会话变量被删除,您的框才会显示。