javascript 在 DIV 外单击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11834657/
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-26 14:29:49  来源:igfitidea点击:

click outside DIV

javascriptjqueryhtml

提问by Mick Asgorther

<body>
    <div id="aaa">
       <div id="bbb">
       </div>
    </div>
</body>


$(#?????).click(function(){

     $('#bbb').hide();

})

http://jsfiddle.net/GkRY2/

http://jsfiddle.net/GkRY2/

What i must use if i want hide #bbb if user click outside box #bbb? But if i click on div #bbb then box is still visible - only outside.

如果用户单击框外#bbb,我想隐藏#bbb,我必须使用什么?但是如果我点击 div #bbb 然后框仍然可见 - 只有在外面。

回答by Fresheyeball

 $('body').click(function(e){
       if( e.target.id == 'bbb' )
          { return true; }
       else
          { $('#bbb').hide(); }

 });

A note of explanation: There are a few ways to do this, either way we need to listen for a click on a parent element, weather it be a direct parent like #aaaor a distant parent like the bodyor the document. This way we can capture clicks that occur outside of #bbb.

记解释:有几个方法可以做到这一点,无论哪种方式,我们需要倾听的父元素上的点击,天气它是一个直接的父母像#aaa或一个遥远的父母像bodydocument。通过这种方式,我们可以捕获发生在#bbb.

Now that we have that we need the .hideto NOT occur if the user did click inside of #bbb. We can do this two ways

现在我们已经知道,.hide如果用户确实在#bbb. 我们可以通过两种方式做到这一点

  1. Stop propagation if the user clicks on #bbb. This will make the click event not 'bubble'up to the parent. That way the click event never reaches the parent and so #bbbwill not hide. I personally don't like this method because stop propagation will so ALL click events from bubbling, and you may have click events that you would like to bubble to a local parent and not a distant parent. Or you may have listeners delegated from a distant parent, which will stop working if click propagation is stopped.

  2. Check for the #bbbelement in the parent listener. This is the method shown above. Basically this listens on a distant parent, and when a click occurs it checks to see if that click is on #bbbspecifically. If it IS NOT on #bbb.hideis fired, otherwise it returns true, so other things that may be tied into the clickevent will continue working. I prefer this method for that reason alone, but secondarily its a-little bit more readable and understandable.

  1. 如果用户单击 ,则停止传播#bbb。这将使点击事件不会“冒泡”到父级。这样点击事件永远不会到达父级,因此#bbb不会隐藏。我个人不喜欢这种方法,因为停止传播会使所有点击事件冒泡,并且您可能有想要冒泡到本地父级而不是远程父级的点击事件。或者,您可能有来自远方的父级委托的侦听器,如果单击传播停止,则该侦听器将停止工作。

  2. 检查#bbb父侦听器中的元素。这是上面显示的方法。基本上,这会侦听远处的父级,当发生点击时,它会检查该点击是否是#bbb专门开启的。如果它 IS NOT on#bbb.hide被触发,否则它返回 true,所以其他可能与click事件相关的东西将继续工作。仅出于这个原因,我更喜欢这种方法,但其次,它的可读性和可理解性要强一些。

Finally the manner in which you check to see if the click originated at #bbbyou have many options. Any will work, the pattern is the real meat of this thing.

最后,您检查点击是否源于#bbb您的方式有很多选择。任何都行,模式是这件事的真正核心。

http://jsfiddle.net/tpBq4///Modded from @Raminson who's answer is very similar.

http://jsfiddle.net/tpBq4///修改自@Raminson,他的回答非常相似。



New suggestion, leverage event bubbling without jQuery.

新建议,在没有 jQuery 的情况下利用事件冒泡。

var isOutSide = true
    bbb       = documment.getElementById('bbb');
document.body.addEventListener('click', function(){
   if(!isOutSide){
       bbb.style.display = 'none';
   }
   isOutSide = true;
});

bbb.addEventListener('click', function(){
   isOutSide = false;
});

回答by Jasper

Catch the clickevent as it bubbles-up to the documentelement. When it hits the documentelement, hide the element. Then in a clickevent handler for the element, stop the propagation of the event so it doesn't reach the documentelement:

捕捉click事件,因为它冒泡到document元素。当它击中document元素时,隐藏元素。然后在click元素的事件处理程序中,停止事件的传播,使其不会到达document元素:

$(function () {
    $(document).on('click', function () {
        $('#bbb').hide();
    });
    $('#bbb').on('click', function (event) {
        event.stopPropagation();
    });
});

Here is a demo: http://jsfiddle.net/KVXNL/

这是一个演示:http: //jsfiddle.net/KVXNL/

Docs for event.stopPropagation(): http://api.jquery.com/event.stopPropagation/

文档event.stopPropagation()http: //api.jquery.com/event.stopPropagation/

回答by Tyler Crompton

I made a plugin that does this. It preserves the value for thiswhere as these other solutions' thisvalue will refer to document.

我做了一个插件来做到这一点。它保留了thiswhere的值,因为这些其他解决方案的this值将引用document

https://github.com/tylercrompton/clickOut

https://github.com/tylercrompton/clickOut

Use:

利用:

$('#bbb').clickOut(function () {
    $(this).hide();
});

回答by undefined

You can use targetproperty of the event object, try the following:

您可以使用target事件对象的属性,请尝试以下操作:

$(document).click(function(e) {
    if (e.target.id != 'bbb') { 
          $('#bbb').hide();
    }
})

DEMO

演示

回答by Simon Edstr?m

This will work

这将工作

$("#aaa").click(function(){

     $('#bbb').hide();

});

$("#bbb").click(function(event){

    event.stopPropagation();
})?

Becouse bbbis inside the aaathe event will "bubbel up to aaa". So you have to stop the bubbling by using the event.stopPropagationwhen bbbis clicked

因为bbbaaa 内,事件将“冒泡到aaa”。所以,你必须通过停止起泡 event.stopPropagationBBB点击

http://jsfiddle.net/GkRY2/5/

http://jsfiddle.net/GkRY2/5/

回答by user2011323

OK

*this is none jquery. you can easly modify it to work with IE

*这不是 jquery。您可以轻松修改它以与 IE 一起使用

first create helper method to facilitate codding don't get confused with JQuery $()

首先创建辅助方法以促进编码不要与 JQuery $() 混淆

    function $g(element) {

    return document.getElementById(element);

    }

create our listener class

创建我们的监听器类

  function globalClickEventListener(obj){

    this.fire = function(event){
        obj.onOutSideClick(event);
        }
    }

let's say we need to capture every click on document body

假设我们需要捕获对文档正文的每次点击

so we need to create listeners array and initialize our work. This method will be called on load

所以我们需要创建监听器数组并初始化我们的工作。此方法将在加载时调用

      function initialize(){

    // $g('body') will return reference to our document body. parameter 'body' is the id of our document body

    $g('body').globalClickEventListeners = new Array();
    $g('body').addGlobalClickEventListener = function (listener)
    {
        $g('body').globalClickEventListeners.push(listener);

    }

    //  capture onclick event on document body and inform all listeners

    $g('body').onclick = function(event) {
        for(var i =0;i < $g('body').globalClickEventListeners.length; i++){
            $g('body').globalClickEventListeners[i].fire(event);
        }
    }

}

after initialization we create event listener and pass reference of the object that needs to know every clcik on our document

初始化后,我们创建事件侦听器并传递需要知道文档中每个 clcik 的对象的引用

    function goListening(){

        var icanSeeEveryClick = $g('myid');
        var lsnr = new globalClickEventListener(icanSeeEveryClick);

       // add our listener to listeners array   

        $g('body').addGlobalClickEventListener(lsnr);

       // add event handling method to div   

        icanSeeEveryClick.onOutSideClick = function (event){
             alert('Element with id : ' + event.target.id + ' has been clicked');
        }

    }

*Take into account the document body height and width

*考虑到文档正文的高度和宽度

*Remove event listeners when you don't need them

*不需要时删除事件侦听器

回答by jroi_web

$(document).click(function(event) { 
    if(!$(event.target).closest('#elementId').length) {
        if($('#elementId').is(":visible")) {
            $('#elementId').hide('fast');
        }
    }        
})

Change the "#elementId" with your div.

使用您的 div 更改“#elementId”。