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

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

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

当前回答

解决方案1

不要使用event.stopPropagation(),因为它会产生一些副作用,只需定义一个简单的标志变量并添加一个if条件。我对此进行了测试,工作正常,没有任何stopPropagation的副作用:

var flag = "1";
$('#menucontainer').click(function(event){
    flag = "0"; // flag 0 means click happened in the area where we should not do any action
});

$('html').click(function() {
    if(flag != "0"){
        // Hide the menus if visible
    }
    else {
        flag = "1";
    }
});

解决方案2

只有一个简单的if条件:

$(document).on('click', function(event){
    var container = $("#menucontainer");
    if (!container.is(event.target) &&            // If the target of the click isn't the container...
        container.has(event.target).length === 0) // ... nor a descendant of the container
    {
        // Do whatever you want to do when click is outside the element
    }
});

其他回答

我读过2021的所有内容,但若并没有错的话,也并没有人提出过这样简单的建议,来解除和删除事件。使用了前面的两个答案和更多的小技巧,所以我把所有的都放在了一个里面(它也可以作为一个参数添加到函数中以传递选择器,以获得更多的弹出窗口)。

也许有人知道这个笑话是有用的。也可以这样做:

<div id="container" style="display:none"><h1>my menu is nice, but it disappears if I click outside it</h1></div>

<script>
  function printPopup() {
    $("#container").css({"display": "block"});
    var remListener = $(document).mouseup(function (e) {
      if ($(e.target).closest("#container").length === 0 &&
          (e.target != $('html').get(0)))
      {
        //alert('closest call');
        $("#container").css({"display": "none"});
        remListener.unbind('mouseup'); // Isn't it?
      }
    });
  }

  printPopup();

</script>

Use:

var go = false;
$(document).click(function(){
    if(go){
        $('#divID').hide();
        go = false;
    }
})

$("#divID").mouseover(function(){
    go = false;
});

$("#divID").mouseout(function (){
    go = true;
});

$("btnID").click( function(){
    if($("#divID:visible").length==1)
        $("#divID").hide(); // Toggle
    $("#divID").show();
});

这对我来说非常及时:

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

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

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

$("#menuscontainer").click(function() {
    $(this).focus();
});
$("#menuscontainer").blur(function(){
    $(this).hide();
});

对我来说很好。