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

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

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

当前回答

这应该是有效的:

$('body').click(function (event) {
    var obj = $(event.target);
    obj = obj['context']; // context : clicked element inside body
    if ($(obj).attr('id') != "menuscontainer" && $('#menuscontainer').is(':visible') == true) {
        //hide menu
    }
});

其他回答

订阅捕获阶段的点击以处理调用preventDefault的点击元素。使用其他名称在文档元素上重新触发它,单击任意位置。

document.addEventListener('click', function (event) {
  event = $.event.fix(event);
  event.type = 'click-anywhere';
  $document.trigger(event);
}, true);

然后,在需要单击外部功能的地方,订阅文档上的单击任意位置事件,并检查单击是否在您感兴趣的元素之外:

$(document).on('click-anywhere', function (event) {
  if (!$(event.target).closest('#smth').length) {
    // Do anything you need here
  }
});

一些注意事项:

您必须使用文档,因为在发生单击的所有元素上触发事件是性能错误。这个功能可以封装到特殊的插件中,在外部点击时调用一些回调。您不能使用jQuery本身订阅捕获阶段。您不需要加载文档来订阅,因为订阅是在文档上进行的,甚至不在其主体上,所以它总是独立于脚本放置和加载状态而存在。

我最后做了这样的事情:

$(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的东西。不管怎样,这对我来说都很好。这正是我想要的。

这对我来说非常有效!!

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

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

它保存一个全局队列(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}

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

$(".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元素内,那么单击或移动菜单本身应该不会有问题。