我正在使用这段代码:

$('body').click(function() {
   $('.form_wrapper').hide();
});

$('.form_wrapper').click(function(event){
   event.stopPropagation();
});

这个HTML:

<div class="form_wrapper">
   <a class="agree" href="javascript:;">I Agree</a>
   <a class="disagree" href="javascript:;">Disagree</a>
</div>

问题是,我有链接在div和当他们不再工作时,点击。


您可能希望检查为主体触发的click事件的目标,而不是依赖于stopPropagation。

喜欢的东西:

$("body").click
(
  function(e)
  {
    if(e.target.className !== "form_wrapper")
    {
      $(".form_wrapper").hide();
    }
  }
);

此外,body元素可能不包括浏览器中显示的整个视觉空间。如果您注意到您的点击没有注册,您可能需要为HTML元素添加点击处理程序。

你最好这样写:

var mouse_is_inside = false;

$(document).ready(function()
{
    $('.form_content').hover(function(){ 
        mouse_is_inside=true; 
    }, function(){ 
        mouse_is_inside=false; 
    });

    $("body").mouseup(function(){ 
        if(! mouse_is_inside) $('.form_wrapper').hide();
    });
});
$(document).click(function(event) {
    if ( !$(event.target).hasClass('form_wrapper')) {
         $(".form_wrapper").hide();
    }
});

这样不行吗?

$("body *").not(".form_wrapper").click(function() {

});

or

$("body *:not(.form_wrapper)").click(function() {

});

更新解决方案为:

使用mouseenter和mouseleave代替 的悬停使用活动事件绑定

var mouseOverActiveElement = false;

$('.active').live('mouseenter', function(){
    mouseOverActiveElement = true; 
}).live('mouseleave', function(){ 
    mouseOverActiveElement = false; 
});
$("html").click(function(){ 
    if (!mouseOverActiveElement) {
        console.log('clicked outside active element');
    }
});
var n = 0;
$("#container").mouseenter(function() {
n = 0;

}).mouseleave(function() {
n = 1;
});

$("html").click(function(){ 
if (n == 1) {
alert("clickoutside");
}
});

甚至溶化:

$("html").click(function(){ 
    $(".wrapper:visible").hide();
});

根据文档,.blur()不仅仅适用于<input>标记。例如:

$('.form_wrapper').blur(function(){
   $(this).hide();
});

你能做的就是将一个点击事件绑定到文档中,如果下拉菜单外的东西被点击,它就会隐藏下拉菜单,但是如果下拉菜单内的东西被点击,它就不会隐藏,所以你的“show”事件(或slidedown或任何显示下拉菜单的东西)

    $('.form_wrapper').show(function(){

        $(document).bind('click', function (e) {
            var clicked = $(e.target);
            if (!clicked.parents().hasClass("class-of-dropdown-container")) {
                 $('.form_wrapper').hide();
            }
        });

    });

然后在隐藏它时,取消绑定单击事件

$(document).unbind('click');

遇到同样的问题,就想出了这个简单的解决方法。它甚至可以递归工作:

$(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();
    }
});
$(document).ready(function() {

$('.headings').click(function () {$('#sub1').css("display",""); });
$('.headings').click(function () {return false;});
$('#sub1').click(function () {return false;});
$('body').click(function () {$('#sub1').css("display","none");

})});

我觉得这样会容易得多。我是这样做的:

$(':not(.form_wrapper)').click(function() {
    $('.form_wrapper').hide();
});

这段代码检测页面上的任何单击事件,然后当且仅当所单击的元素既不是#CONTAINER元素也不是它的后代元素时,隐藏#CONTAINER元素。

$(document).on('click', function (e) {
    if ($(e.target).closest("#CONTAINER").length === 0) {
        $("#CONTAINER").hide();
    }
});

如果你在ios系统上有问题,鼠标up在苹果设备上无法工作。

在jquery mousedown /mouseup工作的ipad?

我用这个:

$(document).bind('touchend', function(e) {
        var container = $("YOURCONTAINER");

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

这是我在另一个线程上找到的jsfiddle,也可以使用esc键:http://jsfiddle.net/S5ftb/404

    var button = $('#open')[0]
    var el     = $('#test')[0]

    $(button).on('click', function(e) {
      $(el).show()
      e.stopPropagation()
    })

    $(document).on('click', function(e) {
      if ($(e.target).closest(el).length === 0) {
        $(el).hide()
      }
    })

    $(document).on('keydown', function(e) {
      if (e.keyCode === 27) {
        $(el).hide()
      }
    })
 $('body').click(function(event) {
    if (!$(event.target).is('p'))
    {
        $("#e2ma-menu").hide();
    }
});

P是元素名。这里也可以传递id、类或元素名。

现场演示与ESC功能

适用于桌面和移动设备

var notH = 1,
    $pop = $('.form_wrapper').hover(function(){ notH^=1; });

$(document).on('mousedown keydown', function( e ){
  if(notH||e.which==27) $pop.hide();
});

如果在某些情况下,你需要确保你的元素在点击文档时是可见的:If ($pop.is(':visible') && (notH||e.which==27)) $pop.hide();

我是这样做的:

var close = true;

$(function () {

    $('body').click (function(){

        if(close){
            div.hide();
        }
        close = true;
    })


alleswasdenlayeronclicknichtschliessensoll.click( function () {   
        close = false;
    });

});
dojo.query(document.body).connect('mouseup',function (e)
{
    var obj = dojo.position(dojo.query('div#divselector')[0]);
    if (!((e.clientX > obj.x && e.clientX <(obj.x+obj.w)) && (e.clientY > obj.y && e.clientY <(obj.y+obj.h))) ){
        MyDive.Hide(id);
    }
});

如果你点击.form_wrapper返回false:

$('body').click(function() {
  $('.form_wrapper').click(function(){
  return false
});
   $('.form_wrapper').hide();
});

//$('.form_wrapper').click(function(event){
//   event.stopPropagation();
//});

将点击事件附加到表单包装器外的顶级元素,例如:

$('#header, #content, #footer').click(function(){
    $('.form_wrapper').hide();
});

这也适用于触摸设备,只是要确保你的选择器列表中没有包含.form_wrapper的父类。

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#hide").click(function(){
    $("p").hide();
  });
  $("#show").click(function(){
    $("p").show();
  });
});
</script>
</head>
<body>
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>

对于像IPAD和IPHONE这样的触摸设备,我们可以使用下面的代码

$(document).on('touchstart', function (event) {
var container = $("YOUR CONTAINER SELECTOR");

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

现场演示

检查单击区域不在目标元素中,也不在它的子元素中

$(document).click(function (e) {
    if ($(e.target).parents(".dropdown").length === 0) {
        $(".dropdown").hide();
    }
});

更新:

jQuery停止传播是最好的解决方案

现场演示

$(".button").click(function(e){
    $(".dropdown").show();
     e.stopPropagation();
});

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

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

(只是添加到prc322的答案。)

在我的例子中,我使用这段代码来隐藏当用户单击适当的选项卡时出现的导航菜单。我发现添加一个额外的条件很有用,即容器外的点击目标不是链接。

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

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

这是因为我网站上的一些链接为页面添加了新内容。如果在添加新内容的同时导航菜单消失了,用户可能会迷失方向。

var exclude_div = $("#ExcludedDiv");; 美元(文档).click(函数(e) { 如果(! exclude_div。Is (e.target)) //如果目标div不是一个你想排除然后添加类隐藏 $ (" .myDiv1 ") .addClass(“隐藏”); });

小提琴

您可以将tabindex设置为父元素<div>,而不是监听DOM上的每一次单击以隐藏一个特定的元素,并监听focusout事件。

设置tabindex将确保在<div>上触发模糊事件(通常不会)。

所以你的HTML看起来是这样的:

<div class="form_wrapper" tabindex="0">
    <a class="agree" href="javascript:;">I Agree</a>
    <a class="disagree" href="javascript:;">Disagree</a>
</div>

你的JS:

$('.form_wrapper').on('focusout', function(event){
    $('.form_wrapper').hide();
});

切换常规和触摸设备

我在这里读了一些答案,并创建了一些代码,我使用div的函数作为弹出气泡。

$('#openPopupBubble').click(function(){
    $('#popupBubble').toggle();

    if($('#popupBubble').css('display') === 'block'){
        $(document).bind('mousedown touchstart', function(e){
            if($('#openPopupBubble').is(e.target) || $('#openPopupBubble').find('*').is(e.target)){
                $(this).unbind(e);
            } 
            else if(!$('#popupBubble').find('*').is(e.target)){
                $('#popupBubble').hide();
                $(this).unbind(e);
            }
        });
    }
});

您还可以使用类使其更加抽象,并根据触发单击事件的按钮选择正确的弹出气泡。

$('body').on('click', '.openPopupBubble', function(){
    $(this).next('.popupBubble').toggle();

    if($(this).next('.popupBubble').css('display') === 'block'){
        $(document).bind('mousedown touchstart', function(e){
            if($(this).is(e.target) || $(this).find('*').is(e.target)){
                $(this).unbind(e);
            } 
            else if(!$(this).next('.popupBubble').find('*').is(e.target)){
                $(this).next('.popupBubble').hide();
                $(this).unbind(e);
            }
        });
    }
});

最流行的答案没有jQuery的解决方案:

document.addEventListener('mouseup', function (e) {
    var container = document.getElementById('your container ID');

    if (!container.contains(e.target)) {
        container.style.display = 'none';
    }
}.bind(this));

MDN: https://developer.mozilla.org/en/docs/Web/API/Node/contains

通过使用这段代码,您可以隐藏尽可能多的项目

var boxArray = ["first element's id","second element's id","nth element's id"];
   window.addEventListener('mouseup', function(event){
   for(var i=0; i < boxArray.length; i++){
    var box = document.getElementById(boxArray[i]);
    if(event.target != box && event.target.parentNode != box){
        box.style.display = 'none';
    }
   }
})

根据prc322的精彩答案构建。

function hideContainerOnMouseClickOut(selector, callback) {
  var args = Array.prototype.slice.call(arguments); // Save/convert arguments to array since we won't be able to access these within .on()
  $(document).on("mouseup.clickOFF touchend.clickOFF", function (e) {
    var container = $(selector);

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
      container.hide();
      $(document).off("mouseup.clickOFF touchend.clickOFF");
      if (callback) callback.apply(this, args);
    }
  });
}

这增加了一些东西……

放置在带有“unlimited”参数的回调函数中 添加了对jquery的.off()的调用,与事件名称空间配对,以便在事件运行后将其从文档中解绑定。 包括触摸端移动功能

我希望这能帮助到一些人!

$(document).ready(function() { $('.modal-container').on('click', function(e) { if(e.target == $(this)[0]) { $(this).removeClass('active'); // or hide() } }); }); .modal-container { display: none; justify-content: center; align-items: center; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.5); z-index: 999; } .modal-container.active { display: flex; } .modal { width: 50%; height: auto; margin: 20px; padding: 20px; background-color: #fff; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="modal-container active"> <div class="modal"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ac varius purus. Ut consectetur viverra nibh nec maximus. Nam luctus ligula quis arcu accumsan euismod. Pellentesque imperdiet volutpat mi et cursus. Sed consectetur sed tellus ut finibus. Suspendisse porttitor laoreet lobortis. Nam ut blandit metus, ut interdum purus.</p> </div> </div>

这么多答案,加一个肯定是一种通行权… 我没有看到当前(jQuery 3.1.1)的答案-所以:

$(function() {
    $('body').on('mouseup', function() {
        $('#your-selector').hide();
    });
});

摘自https://sdtuts.com/click-on-not-specified-element/

现场演示http://demos.sdtuts.com/click-on-specified-element

$(document).ready(function () {
    var is_specified_clicked;
    $(".specified_element").click(function () {
        is_specified_clicked = true;
        setTimeout(function () {
            is_specified_clicked = false;
        }, 200);
    })
    $("*").click(function () {
        if (is_specified_clicked == true) {
//WRITE CODE HERE FOR CLICKED ON OTHER ELEMENTS
            $(".event_result").text("you were clicked on specified element");
        } else {
//WRITE CODE HERE FOR SPECIFIED ELEMENT CLICKED
            $(".event_result").text("you were clicked not on specified element");
        }
    })
})

这个解决方案应该工作得很好,很简单:

jQuery(document).ready(function($) {
    jQuery(document).click(function(event) {
        if(typeof  jQuery(event.target).attr("class") != "undefined") {
            var classnottobeclickforclose = ['donotcountmeforclickclass1', 'donotcountmeforclickclass2','donotcountmeforclickclass3'];
            var arresult = jQuery.inArray(jQuery(event.target).attr("class"), classnottobeclickforclose);
            if (arresult < 0) {
                jQuery(".popup").hide();
            }
        }
    });
});

在上面的代码更改donotcountmeforclickclass1, donotcountmeforclickclass2等类,你已经用来显示弹出或在它的点击弹出不应该影响,所以你必须明确添加类,你正在使用打开弹出。

用popup class更改.popup class。

我在一个搜索框上工作,根据处理的关键字显示自动完成。当我不想点击任何选项,然后我将使用下面的代码隐藏处理的列表,它的工作。

$(document).click(function() {
 $('#suggestion-box').html("");
});

建议框是我的自动完成容器,我显示的值。

在弹出窗口中使用接受的答案时,可能会遇到一些问题。在某些情况下,点击一个随机位置可能会导致不必要的操作,即错误地单击一个按钮可能会将您带到一个新页面。

我不确定这是否是最有效的解决方案,但为了防止这种情况,我建议使用屏幕掩码。确保屏幕掩码位于<body>标签的正下方,这样它就可以覆盖所有的屏幕宽度:100%;高度:100%。还要注意,它的z-index: 99高于所有元素。如果你想让另一个项目或div在屏幕掩码激活时可点击,只需为该项目或div分配更高的z-index。

屏幕掩码最初是不显示的(display:none),当单击(onclick="hidemenu()")时,它调用一个hide函数。

<body>
<div class="screenmask" onclick="hidemenu()" style="position:fixed; width: 100%; height: 100%; top: 0px; right: 0px; display: none; z-index: 99;"></div>

处理“同一页面上多个不同弹出菜单”的javascript函数可能如下所示:

<script>
// an element with onclick="showmenu('id_here')" pops a menu in the screen
function showmenu(id) {  
  var popmenu = document.getElementById(id); // assume popmenu is of class .cardmenu
  $('.cardmenu').hide();   // clear the screen from other popmenus first
  $(popmenu).show();          // pop the desired specific menu
  $('.screenmask').show(); // activate screenmask
}
    
function hidemenu() {      // called when clicked on the screenmask
  $('.cardmenu').hide();   // clear the screen from all the popmenus
  $('.screenmask').hide(); // deactivate screenmask
}
</script>

这么多答案我都用不上。相反,我采取了公认的答案(工作得很好),并缩短为以下(使用后代选择器):

$(document).mouseup(function(e) 
{
    if (!$(e.target).is("#targetSelector,#targetSelector *")) {
        $('#targetSelector').hide();
    }
});

因为它只以用户交互的速度运行,没有给变量赋值

var $container = $("#popup_container"); $container.click(function(e) { if (e.target.id == $container.attr("id")) { $(this).hide(); } }); #popup_container { background: rgba(200,200,200,0.6); width: 100vh; height: 100vh; position: fixed; display: flex; justify-content: center; align-items: center; } #popup { background: yellow; border: 1px solid black; position: absolute; width: 50%; height: 50%; display: flex; justify-content: center; align-items: center; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="popup_container"> <div id="popup"> Popup </div> </div>

https://jsfiddle.net/041pj7re/

为我工作在所有设备上(2023);)

<section class="form-wrapper">
 <div class="popup-container">
  Popup Me
 </div>
</section>



$('.form-wrapper').on('click', function(e) {
  var pop_container = $(".popup-container");

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