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

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

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

当前回答

我读过2021的所有内容,但若并没有错的话,也并没有人提出过这样简单的建议,来解除和删除事件。使用了前面的两个答案和更多的小技巧,所以我把所有的都放在了一个里面(它也可以作为一个参数添加到函数中以传递选择器,以获得更多的弹出窗口)。

也许有人知道这个笑话是有用的。也可以这样做:

<div id="container" style="display:none"><h1>my menu is nice, but it disappears if I click outside it</h1></div>

<script>
  function printPopup() {
    $("#container").css({"display": "block"});
    var remListener = $(document).mouseup(function (e) {
      if ($(e.target).closest("#container").length === 0 &&
          (e.target != $('html').get(0)))
      {
        //alert('closest call');
        $("#container").css({"display": "none"});
        remListener.unbind('mouseup'); // Isn't it?
      }
    });
  }

  printPopup();

</script>

其他回答

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

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

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

使用本机JS API最接近方法的2020解决方案。

document.addEventListener('click',({target})=>{if(!target.lestest('#menupop')){document.querySelector('#menupop').style.display=“无”}})#菜单弹出窗口{宽度:300px;高度:300px;背景色:红色;}<div id=“menupop”>单击外部将关闭此</div>

jQuery().ready(function(){
    $('#nav').click(function (event) {
        $(this).addClass('activ');
        event.stopPropagation();
    });

    $('html').click(function () {
        if( $('#nav').hasClass('activ') ){
            $('#nav').removeClass('activ');
        }
    });
});

标准HTML:

用<标签>包围菜单并获取焦点状态更改。

http://jsfiddle.net/bK3gL/

另外:您可以通过Tab展开菜单。

使用流中断、模糊/聚焦事件或任何其他棘手的技术,只需将事件流与元素的亲属关系匹配即可:

$(document).on("click.menu-outside", function(event){
    // Test if target and it's parent aren't #menuscontainer
    // That means the click event occur on other branch of document tree
    if(!$(event.target).parents().andSelf().is("#menuscontainer")){
        // Click outisde #menuscontainer
        // Hide the menus (but test if menus aren't already hidden)
    }
});

要删除事件侦听器外部的单击,只需执行以下操作:

$(document).off("click.menu-outside");