简体   繁体   English

在DIV外部单击

[英]click outside DIV

<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? 如果用户要在框#bbb之外单击,我想隐藏#bbb,我必须使用什么? But if i click on div #bbb then box is still visible - only outside. 但是,如果我单击div #bbb,则框仍然可见-仅在外部。

 $('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 #aaa or a distant parent like the body or the document . 注释的说明:有几种方法可以执行此操作,无论哪种方法,我们需要监听对父元素的单击,使其成为#aaa类的直接父元素,或者是诸如bodydocument类的遥远父元素。 This way we can capture clicks that occur outside of #bbb . 这样,我们可以捕获在#bbb之外发生的#bbb

Now that we have that we need the .hide to NOT occur if the user did click inside of #bbb . 现在,我们有我们需要的.hide如果用户没有点击的内部不发生#bbb We can do this two ways 我们可以通过两种方式

  1. Stop propagation if the user clicks on #bbb . 如果用户单击#bbb则停止传播。 This will make the click event not 'bubble' up to the parent. 这将使click事件不会“冒泡”到父级。 That way the click event never reaches the parent and so #bbb will not hide. 这样,单击事件就永远不会到达父级,因此#bbb不会隐藏。 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 #bbb element in the parent listener. 检查父侦听器中的#bbb元素。 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 #bbb specifically. 基本上,这会侦听远方的父母,当发生单击时,它会检查该单击是否专门针对#bbb If it IS NOT on #bbb .hide is fired, otherwise it returns true, so other things that may be tied into the click event will continue working. 如果不是上#bbb .hide被触发,否则返回可以绑成真,那么其他的东西click活动将继续工作。 I prefer this method for that reason alone, but secondarily its a-little bit more readable and understandable. 仅出于这个原因,我更喜欢这种方法,但是其次它的一点点更具可读性和可理解性。

Finally the manner in which you check to see if the click originated at #bbb you have many options. 最后,您可以通过多种方式查看点击是否起源于#bbb Any will work, the pattern is the real meat of this thing. 任何都会起作用的,模式才是真正的东西。

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;
});

Catch the click event as it bubbles-up to the document element. click事件冒泡到document元素时,将其捕获。 When it hits the document element, hide the element. 当它碰到document元素时,隐藏该元素。 Then in a click event handler for the element, stop the propagation of the event so it doesn't reach the document element: 然后,在该元素的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/

I made a plugin that does this. 我做了一个插件可以做到这一点。 It preserves the value for this where as these other solutions' this value will refer to document . 它保留了值this地方,因为这些其他解决方案this值将引用document

https://github.com/tylercrompton/clickOut https://github.com/tylercrompton/clickOut

Use: 使用:

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

You can use target property of the event object, try the following: 您可以使用事件对象的target属性,请尝试以下操作:

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

DEMO 演示

This will work 这会起作用

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

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

});

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

    event.stopPropagation();
})​

Becouse bbb is inside the aaa the event will "bubbel up to aaa ". 因为bbbaaa内,所以该事件将“起泡至aaa ”。 So you have to stop the bubbling by using the event.stopPropagation when bbb is clicked 因此,单击bbb时,必须使用event.stopPropagation停止冒泡

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

OK

* this is none jquery. *这不是jquery。 you can easly modify it to work with IE 您可以轻松地对其进行修改以与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 初始化后,我们创建事件侦听器并传递需要了解我们文档中所有信息的对象的引用

    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 *在不需要事件侦听器时将其删除

$(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”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM