[英]How do I hide a modal when the overlay is clicked in vanilla javascript
I'm trying to figure out how to hide the div which is the overlay only when the overlay is clicked and not any of its children (ie: the content):我试图弄清楚如何仅在单击覆盖而不是其任何子项(即:内容)时隐藏作为覆盖的 div:
modal.addEventListener('click', destroy, false);
function destroy(e) {
if (e.target.id === overlay.id) {
window.location.reload(false);
}
}
Your if
condition is working but you don't hide something.您的
if
条件有效,但您没有隐藏任何东西。 For that you could add a class (for example .hidden
) and define for that class display: none
.为此,您可以添加一个 class (例如
.hidden
)并为该 class display: none
。
Working example:工作示例:
const modal = document.querySelector('#modal'); const overlay = document.querySelector('#overlay'); modal.addEventListener('click', destroy, false); function destroy(e) { if (e.target.id === overlay.id) { e.target.classList.add('hidden'); } }
#overlay { height: 50px; background-color: yellow; } p { background-color: red; }.hidden { display: none; }
<div id="modal"> <div id="overlay"> <p>test</p> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.