[英]Hide a div when clicked outside
我的弹出窗口小部件具有以下HTML:
<div id="popup">
<div class="popup-wrapper">
<div class="content">
<h1>TEST</h1>
</div>
</div>
</div>
使用CSS:显示为NONE:
#popup {
display: none;
overflow: auto;
}
#popup .popup-wrapper {
background-color: #0D1014;
background-color: rgba(13,16,20,0.95);
height: 100%; width: 100%;
position: fixed; top: 0; left: 0; right: 0; bottom 0;
}
#popup .content {
background-color: #E8F0F3;
border: 1px solid #FFFFFF;
width: 300px;
position: fixed;
top: 50%; left: 50%;
margin-left: -150px;
margin-top: -140px;
padding: 20px;
overflow: hidden;
border-radius: 5px 5px 5px 5px;
-moz-border-radius: 5px 5px 5px 5px;
-webkit-border-radius: 5px 5px 5px 5px;
-webkit-box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.5);
-moz-box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.5);
box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.5);
}
.no-scroll {
overflow: hidden;
height: 100%; width: 100%;
}
使用JavaScript单击链接时将显示弹出窗口:
$(".popup").on('click', function(e) {
$("#popup").fadeIn(200);
$("body").addClass("no-scroll");
});
问题是,仅单击.popup-wrapper
而不单击.content
时,如何隐藏#popup
?
我自己在20分钟前遇到了这个问题
码:
$("#popup").on('click', function(e) {
if ($(e.target).closest(".content" /*or any other selector here*/).length > 0) {return false;}
$("#popup").fadeOut(200);
$("body").addClass("no-scroll");
});
您可以通过添加以下内容来阻止对.content
任何点击传播 :
$('.content').click(function(e){ e.stopPropagation() })
$('#popup').click(function(){ $(this).fadeOut() })
使用:not
伪选择器过滤掉.content
DIV:
$(".popup-wrapper:not(.content)").click(...)
试试下面的代码:
jQuery('.popup-wrapper').click(function(){
jQuery('#popup').hide();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.