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

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

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

当前回答

我最后做了这样的事情:

$(document).on('click', 'body, #msg_count_results .close',function() {
    $(document).find('#msg_count_results').remove();
});
$(document).on('click','#msg_count_results',function(e) {
    e.preventDefault();
    return false;
});

我在新容器中有一个关闭按钮,用于最终用户友好的UI。为了不通过,我不得不使用return false。当然,有一个A HREF带你去某个地方会很好,或者你可以调用一些ajax的东西。不管怎样,这对我来说都很好。这正是我想要的。

其他回答

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>

您可以监听文档上的单击事件,然后使用.clost()确保#menucontainer不是被单击元素的祖先或目标。

如果不是,则单击的元素位于#menucontainer之外,您可以安全地隐藏它。

$(document).click(function(event) { 
  var $target = $(event.target);
  if(!$target.closest('#menucontainer').length && 
  $('#menucontainer').is(":visible")) {
    $('#menucontainer').hide();
  }        
});

编辑–2017-06-23

如果您计划关闭菜单并希望停止侦听事件,也可以在事件侦听器之后进行清理。此函数将只清理新创建的侦听器,保留文档上的任何其他单击侦听器。使用ES2015语法:

export function hideOnClickOutside(selector) {
  const outsideClickListener = (event) => {
    const $target = $(event.target);
    if (!$target.closest(selector).length && $(selector).is(':visible')) {
        $(selector).hide();
        removeClickListener();
    }
  }

  const removeClickListener = () => {
    document.removeEventListener('click', outsideClickListener);
  }

  document.addEventListener('click', outsideClickListener);
}

编辑–2018-03-11

对于那些不想使用jQuery的人。这是上面的纯vanillaJS(ECMAScript6)代码。

function hideOnClickOutside(element) {
    const outsideClickListener = event => {
        if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
          element.style.display = 'none';
          removeClickListener();
        }
    }

    const removeClickListener = () => {
        document.removeEventListener('click', outsideClickListener);
    }

    document.addEventListener('click', outsideClickListener);
}

const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js 

注:这是基于Alex的评论,仅供使用!元素。包含(event.target)而不是jQuery部分。

但是element.clost()现在也可以在所有主要浏览器中使用(W3C版本与jQuery版本稍有不同)。Polyfills可以在以下位置找到:Element.clost()

编辑–2020-05-21

如果您希望用户能够在元素内部单击并拖动,则在元素外部释放鼠标,而不关闭元素:

      ...
      let lastMouseDownX = 0;
      let lastMouseDownY = 0;
      let lastMouseDownWasOutside = false;

      const mouseDownListener = (event: MouseEvent) => {
        lastMouseDownX = event.offsetX;
        lastMouseDownY = event.offsetY;
        lastMouseDownWasOutside = !$(event.target).closest(element).length;
      }
      document.addEventListener('mousedown', mouseDownListener);

在外部ClickListener中:

const outsideClickListener = event => {
        const deltaX = event.offsetX - lastMouseDownX;
        const deltaY = event.offsetY - lastMouseDownY;
        const distSq = (deltaX * deltaX) + (deltaY * deltaY);
        const isDrag = distSq > 3;
        const isDragException = isDrag && !lastMouseDownWasOutside;

        if (!element.contains(event.target) && isVisible(element) && !isDragException) { // or use: event.target.closest(selector) === null
          element.style.display = 'none';
          removeClickListener();
          document.removeEventListener('mousedown', mouseDownListener); // Or add this line to removeClickListener()
        }
    }

如果您正在为IE和FF 3.*编写脚本,并且您只想知道单击是否发生在某个框区域内,您也可以使用以下内容:

this.outsideElementClick=函数(objEvent,objElement){var objCurrentElement=objEvent.target | | objEvent.srcElement;var blnSideX=false;var blnSideY=false;如果(objCurrentElement.getBoundingClientRect().left>=objElement.getBoundingClientRect().left&&objCurrentElement.getBoundingClientRectblnSideX=真;如果(objCurrentElement.getBoundingClientRect().top>=objElement.getBoundingClientRect().ttop&&objCurrentElement.getBoundingClientRectblnSideY=真;如果(blnSideX&&blnSideY)return false;其他的返回true;}

这是一个更通用的解决方案,它允许监视多个元素,并动态地从队列中添加和删除元素。

它保存一个全局队列(autoCloseQueue)——一个对象容器,用于在外部单击时应关闭的元素。

每个队列对象键都应该是DOM元素id,值应该是一个具有2个回调函数的对象:

 {onPress: someCallbackFunction, onOutsidePress: anotherCallbackFunction}

将其放入文档就绪回调中:

window.autoCloseQueue = {}  

$(document).click(function(event) {
    for (id in autoCloseQueue){
        var element = autoCloseQueue[id];
        if ( ($(e.target).parents('#' + id).length) > 0) { // This is a click on the element (or its child element)
            console.log('This is a click on an element (or its child element) with  id: ' + id);
            if (typeof element.onPress == 'function') element.onPress(event, id);
        } else { //This is a click outside the element
            console.log('This is a click outside the element with id: ' + id);
            if (typeof element.onOutsidePress == 'function') element.onOutsidePress(event, id); //call the outside callback
            delete autoCloseQueue[id]; //remove the element from the queue
        }
    }
});

然后,当创建id为“menuscontainer”的DOM元素时,只需将此对象添加到队列:

window.autoCloseQueue['menuscontainer'] = {onOutsidePress: clickOutsideThisElement}

作为Art这个伟大答案的包装,并使用OP最初要求的语法,这里有一个jQuery扩展,它可以记录在集合元素之外是否发生了单击。

$.fn.clickOutsideThisElement = function (callback) {
    return this.each(function () {
        var self = this;
        $(document).click(function (e) {
            if (!$(e.target).closest(self).length) {
                callback.call(self, e)
            }
        })
    });
};

然后你可以这样打电话:

$("#menuscontainer").clickOutsideThisElement(function() {
    // handle menu toggle
});

这是小提琴演示