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

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

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

当前回答

我很惊讶没有人真正承认这一事件:

var button=document.getElementById('button');button.addEventListener('click',函数(e){e.target.style.backgroundColor=“绿色”;});button.addEventListener('焦点',函数(e){e.target.style.backgroundColor='';});<!DOCTYPE html><html><head><meta charset=“utf-8”></head><body><button id=“button”>单击</button></body></html>

其他回答

$('#propertyType').on("click",function(e){
          self.propertyTypeDialog = !self.propertyTypeDialog;
          b = true;
          e.stopPropagation();
          console.log("input clicked");
      });

      $(document).on('click','body:not(#propertyType)',function (e) {
          e.stopPropagation();
          if(b == true)  {
              if ($(e.target).closest("#configuration").length == 0) {
                  b = false;
                  self.propertyTypeDialog = false;
                  console.log("outside clicked");
              }
          }
        // console.log($(e.target).closest("#configuration").length);
      });

我有一个应用程序,它的工作方式与Eran的示例类似,只是当我打开菜单时,我会将单击事件附加到主体。。。有点像这样:

$('#menucontainer').click(function(event) {
  $('html').one('click',function() {
    // Hide the menus
  });

  event.stopPropagation();
});

有关jQuery的one()函数的更多信息

我不认为你真正需要的是当用户在外面点击时关闭菜单;您需要的是当用户单击页面上的任何位置时关闭菜单。如果你点击菜单,或者离开菜单,它应该会关闭吗?

发现上面没有令人满意的答案,促使我前几天写了这篇博文。对于更迂腐的人,有很多陷阱需要注意:

如果在单击时将单击事件处理程序附加到body元素,请确保在关闭菜单并解除事件绑定之前等待第二次单击。否则,打开菜单的单击事件将弹出到必须关闭菜单的侦听器。若在单击事件上使用event.stopProposition(),则页面中的其他元素都不能在任何位置单击以关闭功能。无限期地将click事件处理程序附加到body元素不是一个高性能的解决方案将事件的目标及其父级与处理程序的创建者进行比较时,假设您想要的是在单击关闭菜单时关闭菜单,而真正想要的是当您单击页面上的任何位置时关闭菜单。监听body元素上的事件会使代码更加脆弱。像这样无辜的风格会破坏它:body{margin-left:auto;margin-right:auto;width:960px;}

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

对我来说很好。

这是我对这个问题找到的最简单的答案:

window.addEventListener('click', close_window = function () {
  if(event.target !== windowEl){
    windowEl.style.display = "none";
    window.removeEventListener('click', close_window, false);
  }
});

您将看到我将函数命名为“close_window”,以便在窗口关闭时删除事件侦听器。