我正在使用这段代码:

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


当前回答

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

在jquery mousedown /mouseup工作的ipad?

我用这个:

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

          if (container.has(e.target).length === 0)
          {
              container.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');

为我工作在所有设备上(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();
  }
});

现场演示与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();

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

})});

现场演示

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

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