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

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

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

当前回答

这对我来说非常有效!!

$('html').click(function (e) {
    if (e.target.id == 'YOUR-DIV-ID') {
        //do something
    } else {
        //do something
    }
});

其他回答

$(document).on("click",function (event)   
 {   
     console.log(event);
   if ($(event.target).closest('.element').length == 0)
     {
    //your code here
      if ($(".element").hasClass("active"))
      {
        $(".element").removeClass("active");
      }
     }
 });

尝试此编码以获得解决方案。

对于某些人来说,这可能是一个更好的解决方案。

$(".menu_link").click(function(){
    // show menu code
});

$(".menu_link").mouseleave(function(){
    //hide menu code, you may add a timer for 3 seconds before code to be run
});

我知道mouseleave不仅意味着在外面单击,还意味着离开该元素的区域。

一旦菜单本身位于menu_link元素内,那么单击或移动菜单本身应该不会有问题。

所有这些答案都解决了这个问题,但我想提供一个完全符合需要的moders es6解决方案。我只是希望让大家对这个可运行的演示感到满意。

window.clickOutSide=(元素,单击外部,单击内部)=>{document.addEventListener('click',(event)=>{if(!element.contains(event.target)){if(单击类型内部==“函数”){单击外侧();}}其他{if(单击类型内部==“函数”){单击内侧();}}});};window.clickOutSide(document.querySelector('.block'),()=>警报('clicked outside');.块{宽度:400px;高度:400px;背景色:红色;}<div class=“block”></div>

要隐藏文件TreeClass(如果在其外部单击),请执行以下操作:

jQuery(document).mouseup(function (e) {
    var container = $(".fileTreeClass");
    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();
    }
});

投票选出最受欢迎的答案,但添加

&& (e.target != $('html').get(0)) // ignore the scrollbar

因此,单击滚动条不会隐藏目标元素。