Javascript 每当我在元素外部单击时,它都应该关闭

Javascript 每当我在元素外部单击时,它都应该关闭,javascript,jquery,html,django,Javascript,Jquery,Html,Django,我试图在每次单击外部时隐藏通知列表,但没有成功。我试过不同的密码。class=通知应该在我单击class=通知时看到,而在我单击外部时应该隐藏 此代码hide class=当我单击外部时通知主div JS HTML 试试这个 $('.notification').on('click', function(event){ $(this).find('.counter').hide(); $(this).find('.notifications').toggleClass('hidd

我试图在每次单击外部时隐藏通知列表,但没有成功。我试过不同的密码。class=通知应该在我单击class=通知时看到,而在我单击外部时应该隐藏

此代码hide class=当我单击外部时通知主div

JS

HTML

试试这个

$('.notification').on('click', function(event){
    $(this).find('.counter').hide();
    $(this).find('.notifications').toggleClass('hidden');
});


$(document).on('click', function(e) {
    if (!e.target.hasClass('notification')) {
      $('.notifications').hide();
    }
});

尝试将事件侦听器添加到正文而不是文档

试试这个

var notification = document.getElementsByClassName("notification")[0];
window.onclick = function(event) {
    if (event.target == notification) {
        notification.style.display = "none";
    }
}
您必须尝试mouseup事件以获取目标div并根据您的需求隐藏/显示。阅读更多关于

检查以下代码以在单击父div.notification时显示.notifications div,如果在div外部单击,则应隐藏.notifications div

$'.notification'。单击时,functionevent{ $this.find'.counter'.hide; $'.notifications.removeClass'hidden'; }; $document.mouseupffunction e{ var容器=$'.notifications'; if!container.ise.target&&container.hase.target.length==0{ $'.notifications'.addClass'hidden'; } }; .通知{ 背景:5fba7d; 颜色:白色; 填充:15px 20px; } .通知{ 背景:白色; 边框:1px纯绿色; 颜色:白色; 填充:5px20px; } .柜台{ 填充物:5px; 边界半径:20px; 背景:ffffff; 位置:绝对位置; 左:110像素; 字体大小:12px; 颜色:5fba7d; 顶部:10px; } .隐藏{ 显示:无; } 100
$(".notification").on("blur", function(){
   $(".notification").hide();
});
$('.notification').on('click', function(event){
    $(this).find('.counter').hide();
    $(this).find('.notifications').toggleClass('hidden');
});


$(document).on('click', function(e) {
    if (!e.target.hasClass('notification')) {
      $('.notifications').hide();
    }
});
$('body').on('click', function() {
    $('.notifications').hide();
}
var notification = document.getElementsByClassName("notification")[0];
window.onclick = function(event) {
    if (event.target == notification) {
        notification.style.display = "none";
    }
}