在外部单击时隐藏 div [英] Hide a div when clicked outside of it

查看:18
本文介绍了在外部单击时隐藏 div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This question has been asked multiple times, however none of the answers seem to work for me.

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 时,它也会消失,不知道为什么,但确实如此.
还有什么可能有用的吗?

Yet whenever i click on the div it also disappears, no clue why but it does.
Any thing else that might work?

推荐答案

由于你的target有id=info,所以你可以试试:

As your target has id=info, so you can try:

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

这篇关于在外部单击时隐藏 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆