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

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

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

当前回答

这种情况的简单解决方案是:

$(document).mouseup(function (e)
{
    var container = $("YOUR SELECTOR"); // Give you class or ID
    
    if (!container.is(e.target) &&            // If the target of the click is not the desired div or section
        container.has(e.target).length === 0) // ... nor a descendant-child of the container
    {
        container.hide();
    }
});

如果在div单击事件之外触发,上述脚本将隐藏div。

其他回答

我在YUI 3中是这样做的:

// Detect the click anywhere other than the overlay element to close it.
Y.one(document).on('click', function (e) {
    if (e.target.ancestor('#overlay') === null && e.target.get('id') != 'show' && overlay.get('visible') == true) {
        overlay.hide();
    }
});

我正在检查祖先是否不是小部件元素容器,如果目标不是打开控件/元素的对象,如果我想关闭的小部件/元素已经打开(不那么重要)。

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

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

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

要隐藏文件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

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

如果有人好奇这里是javascript解决方案(es6):

window.addEventListener('mouseup', e => {
        if (e.target != yourDiv && e.target.parentNode != yourDiv) {
            yourDiv.classList.remove('show-menu');
            //or yourDiv.style.display = 'none';
        }
    })

和es5,以防万一:

window.addEventListener('mouseup', function (e) {
if (e.target != yourDiv && e.target.parentNode != yourDiv) {
    yourDiv.classList.remove('show-menu'); 
    //or yourDiv.style.display = 'none';
}

});