[英]jQuery: hide() box when clicking on body but not() on element itself?
I have a <a href="#" id="btn">Show Box</a>
somwhere in my DOM. 我的DOM中有一个<a href="#" id="btn">Show Box</a>
。 Additionally I have a div#overlay
that is by default set to display:none;
另外我有一个div#overlay
,默认情况下设置为display:none;
. 。
// Toggle Overlay
$('#btn').click(function(e) {
e.preventDefault();
$('#overlay').toggle();
})
$('body').not('#btn, #overlay').click(function() {
if ( $('#overlay').is(':visible') ) $('#overlay').hide();
});
Why is this not working? 为什么这不起作用? I want the #btn
to toggle() the overlay when clicking it. 我希望#btn
在点击时切换叠加()。 However when the overlay is visible and I click anywhere on the document (except the #btn
itself or the #overlay
) I want the overlay also to be hidden. 但是当叠加层可见时我单击文档上的任何位置( #btn
本身或#overlay
)我希望隐藏叠加层。
You are capturing a click
on the body
which itself is never #btn
or #overlay
, and so it does not work as expected. 您正在捕获本身永远不会 #btn
或#overlay
的body
上的click
,因此它无法按预期工作。 What you need to check against instead is event.target
你需要检查的是event.target
ie 即
$('body').click(function(e) {
var target = $(e.target);
if(!target.is('#btn') && !target.is('#overlay')) {
if ( $('#overlay').is(':visible') ) $('#overlay').hide();
}
});
Use event.target.id
for comparing clicked area's id
使用event.target.id
比较单击区域的id
$('body').click(function(e) {
if(e.target.id != 'btn' && e.target.id != 'overlay')
if ( $('#overlay').is(':visible') ) $('#overlay').hide();
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.