在其外部单击时隐藏div

时间:2012-07-18 15:59:36

标签: jquery html onclick hide

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

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时它也会消失,不知道为什么会这样。但是 还有什么可能有用吗?

6 个答案:

答案 0 :(得分:31)

由于您的目标有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();
    }
});

答案 1 :(得分:4)

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元素。

答案 2 :(得分: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){
  ...
});

答案 3 :(得分:3)

试试这段代码,这对我来说是最好的。

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

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

答案 4 :(得分:0)

您可以添加一个类,仅用于检查鼠标单击特定div或该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
    }
});

答案 5 :(得分:-1)

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

$(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

相关问题