我正在使用这段代码:

$('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和当他们不再工作时,点击。


当前回答

你能做的就是将一个点击事件绑定到文档中,如果下拉菜单外的东西被点击,它就会隐藏下拉菜单,但是如果下拉菜单内的东西被点击,它就不会隐藏,所以你的“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');

其他回答

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

在jquery mousedown /mouseup工作的ipad?

我用这个:

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

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

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

喜欢的东西:

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

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

 $('body').click(function(event) {
    if (!$(event.target).is('p'))
    {
        $("#e2ma-menu").hide();
    }
});

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

现场演示

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

$(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的精彩答案构建。

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()的调用,与事件名称空间配对,以便在事件运行后将其从文档中解绑定。 包括触摸端移动功能

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