我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。

jQuery是否可以实现这样的功能?

$("#menuscontainer").clickOutsideThisElement(function() {
    // Hide the menus
});

当前回答

我在一些jQuery日历插件中找到了这个方法。

function ClickOutsideCheck(e)
{
  var el = e.target;
  var popup = $('.popup:visible')[0];
  if (popup==undefined)
    return true;

  while (true){
    if (el == popup ) {
      return true;
    } else if (el == document) {
      $(".popup").hide();
      return false;
    } else {
      el = $(el).parent()[0];
    }
  }
};

$(document).bind('mousedown.popup', ClickOutsideCheck);

其他回答

$('html').click(function(){//隐藏菜单(如果可见)});$('#menucontainer').click(函数(事件){event.stopPropagation();});<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><html><button id=“#menucontainer”>确定</button></html>

注意:应该避免使用stopPropagation,因为它会破坏DOM中的正常事件流。有关更多信息,请参阅这篇CSS技巧文章。请考虑改用此方法。

将单击事件附加到关闭窗口的文档正文。将一个单独的单击事件附加到容器,以停止传播到文档正文。

$(window).click(function() {
  //Hide the menus if visible
});

$('#menucontainer').click(function(event){
  event.stopPropagation();
});
$("#menuscontainer").click(function() {
    $(this).focus();
});
$("#menuscontainer").blur(function(){
    $(this).hide();
});

对我来说很好。

该事件具有元素的名为event.path的属性,该属性是“以树顺序列出其所有祖先的静态有序列表”。要检查事件是否源自特定DOM元素或其子元素之一,只需检查该特定DOM元素的路径。它还可以用于通过在some函数中对元素检查进行逻辑“或”运算来检查多个元素。

$(“body”).click(函数){target=document.getElementById(“main”);flag=event.path.some(函数(el,i,arr){返回(el==目标)})if(标志){console.log(“内部”)}其他{console.log(“外部”)}});#主要的,主要的{显示:内联块;背景:黄色;}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><div id=“main”><ul><li>测试总管</li><li>测试总管</li><li>测试总管</li><li>测试总管</li><li>测试总管</li></ul></div><div id=“main2”>外部主管道</div>

所以你的情况应该是

$("body").click(function() {
  target = $("#menuscontainer")[0];
  flag = event.path.some(function(el, i, arr) {
    return (el == target)
  });
  if (!flag) {
    // Hide the menus
  }
});

我在以下方面取得了成功:

var $menuscontainer = ...;

$('#trigger').click(function() {
  $menuscontainer.show();

  $('body').click(function(event) {
    var $target = $(event.target);

    if ($target.parents('#menuscontainer').length == 0) {
      $menuscontainer.hide();
    }
  });
});

逻辑是:当显示#菜单容器时,仅当(单击的)目标不是它的子对象时,才将一个单击处理程序绑定到隐藏#菜单容器的主体。