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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:36:55  来源:igfitidea点击:

jQuery: hide() box when clicking on body but not() on element itself?

javascriptjquery

提问by matt

I have a <a href="#" id="btn">Show Box</a>somwhere in my DOM. Additionally I have a div#overlaythat 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 #btnto toggle() the overlay when clicking it. However when the overlay is visible and I click anywhere on the document (except the #btnitself or the #overlay) I want the overlay also to be hidden.

为什么这不起作用?我希望#btn在单击时切换()覆盖。但是,当叠加层可见并且我单击文档上的任意位置(除了#btn本身或#overlay)时,我希望叠加层也被隐藏。

回答by techfoobar

You are capturing a clickon the bodywhich itself is never#btnor #overlay, and so it does not work as expected. What you need to check against instead is event.target

您捕捉clickbody其本身是从来没有#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.idfor 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();
})