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

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

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

当前回答

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

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

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

其他回答

作为一种变体:

var $menu = $('#menucontainer');
$(document).on('click', function (e) {

    // If element is opened and click target is outside it, hide it
    if ($menu.is(':visible') && !$menu.is(e.target) && !$menu.has(e.target).length) {
        $menu.hide();
    }
});

它在停止事件传播方面没有问题,并且更好地支持同一页面上的多个菜单,其中当第一个菜单打开时,单击第二个菜单将使stopPropagation解决方案中的第一个菜单保持打开状态。

功能:

$(function() {
    $.fn.click_inout = function(clickin_handler, clickout_handler) {
        var item = this;
        var is_me = false;
        item.click(function(event) {
            clickin_handler(event);
            is_me = true;
        });
        $(document).click(function(event) {
            if (is_me) {
                is_me = false;
            } else {
                clickout_handler(event);
            }
        });
        return this;
    }
});

用法:

this.input = $('<input>')
    .click_inout(
        function(event) { me.ShowTree(event); },
        function() { me.Hide(); }
    )
    .appendTo(this.node);

功能非常简单:

ShowTree: function(event) {
    this.data_span.show();
}
Hide: function() {
    this.data_span.hide();
}

我只是想让@Pistos的回答更加明显,因为它隐藏在评论中。

这个解决方案非常适合我

var elementToToggle = $('.some-element');
$(document).click( function(event) {
  if( $(event.target).closest(elementToToggle).length === 0 ) {
    elementToToggle.hide();
  }
});

在CoffeeScript中:

elementToToggle = $('.some-element')
$(document).click (event) ->
  if $(event.target).closest(elementToToggle).length == 0
    elementToToggle.hide()

经过研究,我找到了三种可行的解决方案

第一种解决方案

<script>
    //The good thing about this solution is it doesn't stop event propagation.

    var clickFlag = 0;
    $('body').on('click', function () {
        if(clickFlag == 0) {
            console.log('hide element here');
            /* Hide element here */
        }
        else {
            clickFlag=0;
        }
    });
    $('body').on('click','#testDiv', function (event) {
        clickFlag = 1;
        console.log('showed the element');
        /* Show the element */
    });
</script>

第二种解决方案

<script>
    $('body').on('click', function(e) {
        if($(e.target).closest('#testDiv').length == 0) {
           /* Hide dropdown here */
        }
    });
</script>

第三种解决方案

<script>
    var specifiedElement = document.getElementById('testDiv');
    document.addEventListener('click', function(event) {
        var isClickInside = specifiedElement.contains(event.target);
        if (isClickInside) {
          console.log('You clicked inside')
        }
        else {
          console.log('You clicked outside')
        }
    });
</script>

如果有人好奇这里是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';
}

});