在 div 外部单击时隐藏它

新手上路,请多包涵

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

div的css如下:

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

我尝试使用以下代码:

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

$(document).click(function(){
  $("#info").hide();
});

以及这段代码:

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

    if (container.has(e.target).length === 0) {
        container.hide();
    }
});

然而,每当我点击 div 它也会消失,不知道为什么但它确实消失了。

还有其他可能有用的东西吗?

原文由 Gooey 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 278
2 个回答

由于您的目标有 id=info ,因此您可以尝试:

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

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

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

您也可以尝试:

 $(document).click(function() {

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

});

根据评论

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

原文由 thecodeparadox 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

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

 $(document).on("mouseup touchend",function(e){
  ...
});

原文由 Andy Lorenz 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题