隐藏一个div当它的外面点击(Hide a div when clicked outside of

2019-06-26 09:22发布

这个问题已经被问多次,但是没有一个答案似乎为我工作。

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

然而,每当我点击它也消失的股利,不知道为什么,但它确实。
任何其他的事情可能的工作?

Answer 1:

当你的目标有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();
    }
});


Answer 2:

附加的onclick事件处理程序document对象:

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

演示: http://jsfiddle.net/aUjRG/

这里是纯JavaScript的解决方案,以帮助您更好地了解它的发生:

function hideInfo(){
    if(window.event.srcElement.id != 'info'){
        document.getElementById('info').style.display = 'none';
    }
}

document.onclick = hideInfo;

演示: http://jsfiddle.net/mmzc8/

这两种解决方案会检查用户点击的地方是用的ID的元素info 。 假设用户没有点击的info元素,然后隐藏info元素。



Answer 3:

为确保您有过在iPad上有效的解决方案,那么你需要使用下面的函数,而不是触发:

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

同样,如果你正在寻找盖掉鼠标松开,加上“touchend”:

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


Answer 4:

试试这个代码,这是最适合我。

jQuery('.button_show_container').click(function(e) {
    jQuery('.container').slideToggle('fast'); 
    e.stopPropagation();
});

jQuery(document).click(function() {
        jQuery('.container').slideUp('fast');
});


Answer 5:

您可以在鼠标仅选中添加类单击div元素内的特定格或任何用户点击与否。

$(document).click(function(e){            
    if ( !$(e.target).hasClass("[class name for check]") &&
         $("[element class or id]").css("display")=="block" ) {
            //...code if clicked out side div
    }
});


Answer 6:

尝试以下解决方案。 它甚至工作递归:

$(document).mouseup(function(e) 
{
    var container = $("YOUR CONTAINER SELECTOR");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});

参考- https://stackoverflow.com/a/7385673/3910232



文章来源: Hide a div when clicked outside of it