在其外部单击时隐藏div

Goo*_*oey 17 html jquery onclick hide

这个问题已被多次询问,但是没有一个答案似乎对我有用.

div的css如下:

#info{
  display: none;
  position: fixed;
  z-index: 500;
  height: 50%;
  width: 60%;
  overflow: auto;
  background: rgba(187, 187, 187, .8);
}
Run Code Online (Sandbox Code Playgroud)

我试着使用以下代码:

$("#info").click(function(e){
  e.stopPropagation();
});

$(document).click(function(){
  $("#info").hide();
});
Run Code Online (Sandbox Code Playgroud)

以及这段代码:

$(document).mouseup(function (e){
    var container = $("#info");

    if (container.has(e.target).length === 0) {
        container.hide();
    }
});
Run Code Online (Sandbox Code Playgroud)

然而,每当我点击div它也消失,没有线索为什么,但它确实.
还有什么可能有用吗?

the*_*dox 31

正如您的目标一样id=info,您可以尝试:

$(document).click(function(e) {

  // check that your clicked
  // element has no id=info

  if( e.target.id != 'info') {
    $("#info").hide();
  }
});
Run Code Online (Sandbox Code Playgroud)

你也可以尝试:

$(document).click(function() {

  if( this.id != 'info') {
    $("#info").hide();
  }

});
Run Code Online (Sandbox Code Playgroud)

根据评论

$(document).click(function(e) {

    // check that your clicked
    // element has no id=info
    // and is not child of info
    if (e.target.id != 'info' && !$('#info').find(e.target).length) {
        $("#info").hide();
    }
});
Run Code Online (Sandbox Code Playgroud)


And*_*enz 5

为确保您的解决方案也适用于 iPad,您需要改用以下函数触发器:

$(document).on("mousedown touchstart",function(e){
  var $info = $('#info');
  if (!$info.is(e.target) && $info.has(e.target).length === 0) {
    $info.hide();
  }
});
Run Code Online (Sandbox Code Playgroud)

同样,如果您想掩盖 mouseup,请添加“touchend”:

$(document).on("mouseup touchend",function(e){
  ...
});
Run Code Online (Sandbox Code Playgroud)