简体   繁体   English

用户何时在div之外单击时的jQuery事件?

[英]JQuery Event for when user clicks outside a div?

Is there any event that can be called whenever the user clicks outside the div to hide that div? 每当用户在div之外单击以隐藏该div时,是否可以调用任何事件?

I tried using $(document).click() , however that one is called even when the user clicks the link which is supposed to show the div. 我尝试使用$(document).click() ,但是即使用户单击应该显示div的链接,该调用也会被调用。 Hence, the click handler event shows the div, and immediately $(document).click() hides it, which means the div is never displayed. 因此,单击处理程序事件将显示div,并且$(document).click()立即将其隐藏,这意味着将永远不会显示div。

Ideas? 有想法吗?

You can try delegating the onclick event handler to the body element (or other suitable parent container) and test for whether the target element is the reveal link: 您可以尝试将onclick事件处理函数委派给body元素(或其他合适的父容器),并测试目标元素是否为揭示链接:

$("body").click(function(e) {
    if(e.target.id == "idOfLinkToShowDiv") {
        $("#idOfTheDiv").show();
    } else {
        $("#idOfTheDiv").hide();
    }
});

The above can be shortened using .toggle : 可以使用.toggle缩短以上.toggle

$("body").click(function(e) {
    $("#idOfTheDiv").toggle(e.target.id == "idOfLinkToShowDiv");
});

Another way: 其他方式:

$("body").click(function() {
    $("#idOfTheDiv").hide();
});

$(".showLink").click(function(e) {
    e.stopPropagation();
    $("#idOfTheDiv").show();
});

When any element is clicked, check if the ID of the element matches the one you want to hide. 单击任何元素后,请检查该元素的ID是否与您要隐藏的元素匹配。 If it doesn't, hide it. 如果没有,请将其隐藏。

$("*").click(function(){
    if(this.id === "hideMe"){
        return false;
    }
    else{
        $("#hideMe").hide();
    }
});

Check out demo on jsFiddle jsFiddle上查看演示

Yes. 是。 After you display the div, only then bind the click event to hide the div (to the document body). 显示div之后,只有绑定click事件才能隐藏div(到文档正文)。 Then, on the displayed div itself, catch click() event, and prevent propagation on div click(). 然后,在显示的div本身上,捕获click()事件,并防止在div click()上传播。 Any click outside the div will hide, and any click inside will not bubble to the document. div外部的任何单击都将隐藏,内部的任何单击都不会冒泡到文档中。

function hideDiv(){
    $('#someDiv').hide();
    $(document.body).unbind('click',hideDiv);
}

$('#someLink').click(function(){
    $('#someDiv').show().click(function(e){ e.stopPropagation(); });
    $(document.body).bind('click',hideDiv);
});

One soluation is the check which element is clicked. 一种解决方法是检查单击了哪个元素。

Another solution might be: 另一个解决方案可能是:

<body>
  <div class="infopane"></div>
  <div class="wrapper">
    content of page
  </div>
</body>

So I can do: 所以我可以做:

$('.wrapper').click(function() {
  $('.infopane').hide();
});

You are looking for the outside events plugin. 您正在寻找外部事件插件。 Super easy to use 超级好用

http://benalman.com/projects/jquery-outside-events-plugin/ http://benalman.com/projects/jquery-outside-events-plugin/

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

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