javascript jQuery:点击身体时隐藏()框而不是()在元素本身上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15386686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: hide() box when clicking on body but not() on element itself?
提问by matt
I have a <a href="#" id="btn">Show Box</a>
somwhere in my DOM. Additionally I have a div#overlay
that is by default set to display:none;
.
<a href="#" id="btn">Show Box</a>
我的 DOM 中有一个地方。另外我有一个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. 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
在单击时切换()覆盖。但是,当叠加层可见并且我单击文档上的任意位置(除了#btn
本身或#overlay
)时,我希望叠加层也被隐藏。
回答by techfoobar
You are capturing a click
on the body
which itself is never#btn
or #overlay
, and so it does not work as expected. What you need to check against instead is event.target
您捕捉click
在body
其本身是从来没有#btn
或#overlay
,所以这是行不通的预期。你需要检查的是event.target
i.e.
IE
$('body').click(function(e) {
var target = $(e.target);
if(!target.is('#btn') && !target.is('#overlay')) {
if ( $('#overlay').is(':visible') ) $('#overlay').hide();
}
});
回答by Anujith
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();
})