使用 window.addEventListener 隐藏 div 不起作用



我创建了一种包含通知的通知div,当用户点击通知图标时,它会显示出来,我想做一些事情,比如如果用户点击了不属于这个通知容器的地方,容器就会隐藏起来,用下拉菜单它可以工作,但用这个div它不可以,我不知道为什么。。。有人可以帮忙吗?有人知道我做错了什么吗?

这是容器HTML:

<div class="notifications-container">
<div class="notifications-container-top-bar">
<span>Notyfications</span>
<div class="btns">
<div class="seenAll">
<img src="static/img/icons/checkedIcon.svg" alt="Seen all btn">
</div>
<div class="closeNotifications">
<img src="static/img/icons/menu/close.svg" alt="Close">
</div>
</div>
</div>
<div class="noNotif">
<p>No new notifications</p>
</div>
<div class="notifications-container-list">
// notification items here
</div>
<div class="notifications-container-bottom-bar">
<p id="loadMoreNotif">See more</p>
</div>
</div>

此容器的默认css为display:none;并且在用户点击通知图标后,它得到了包含display的活动类:block;

当用户点击某个不属于通知容器的地方时,我需要删除活动类,这就是我的js看起来像的原因

const notifContainer = document.getElementsByClassName("notifications-container")[0];
openNotif.addEventListener("click", ()=>{ //it works
notifContainer.classList.add("active");
});
window.addEventListener('click', function(e) {
if (!notifContainer.contains(e.target)) {
notifContainer.classList.remove('active');
}
});

它不起作用,在我添加窗口事件侦听器后,容器将不再打开。有什么想法吗?

当您单击openNotif时,您的窗口单击事件会被触发,因此正在进行的是添加然后删除活动类。在移除属性的函数中,您应该检查event.target不是触发"的元素或选择器;显示";行动

最新更新