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

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

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

当前回答

对于那些希望将一个简短的解决方案集成到JS代码中的人来说——一个没有JQuery的小型库:

用法:

// demo code
var htmlElem = document.getElementById('my-element')
function doSomething(){ console.log('outside click') }

// use the lib
var removeListener = new elemOutsideClickListener(htmlElem, doSomething);

// deregister on your wished event
$scope.$on('$destroy', removeListener);

下面是库:


function elemOutsideClickListener (element, outsideClickFunc, insideClickFunc) {
   function onClickOutside (e) {
      var targetEl = e.target; // clicked element
      do {
         // click inside
         if (targetEl === element) {
            if (insideClickFunc) insideClickFunc();
            return;

         // Go up the DOM
         } else {
            targetEl = targetEl.parentNode;
         }
      } while (targetEl);

      // click outside
      if (!targetEl && outsideClickFunc) outsideClickFunc();
   }

   window.addEventListener('click', onClickOutside);

   return function () {
      window.removeEventListener('click', onClickOutside);
   };
}

我从这里获取代码并将其放在函数中:https://www.w3docs.com/snippets/javascript/how-to-detect-a-click-outside-an-element.html

其他回答

最简单的方法:mouseleave(function())

更多信息:https://www.w3schools.com/jquery/jquery_events.asp

const button=document.querySelector('button')const box=document.querySelector('.box');常量切换=事件=>{event.stopPropagation();if(!event.target.closest('.box')){console.log('单击外部');box.classList.tggle(“活动”);box.classList.contains('active')? document.addEventListener('click',切换):document.removeEventListener(“单击”,切换);}其他{console.log('单击内部');}}button.addEventListener('单击',切换);.box格式{位置:绝对;显示:无;页边空白:8px;填充:20px;背景:浅灰色;}.box激活{显示:块;}<button>切换框</button><div class=“box”><form action=“”><input-type=“text”><button type=“button”>搜索</button></form></div>

只是一个警告,使用这个:

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

$('#menucontainer').click(function(event){
  event.stopPropagation();
});

它阻止RubyonRails UJS驱动程序正常工作。例如,link_to“click”、“/url”、:method=>:delete将不起作用。

这可能是一种变通方法:

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

$('#menucontainer').click(function(event){
  if (!$(event.target).data('method')) {
    event.stopPropagation();
  }
});

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

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

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

检查窗口单击事件目标(它应该传播到窗口,只要它没有在其他地方被捕获),并确保它不是任何菜单元素。如果不是,那么你就在菜单之外。

或者检查单击的位置,看看它是否包含在菜单区域中。