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

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

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

当前回答

这是我的代码:

// Listen to every click
$('html').click(function(event) {
    if ( $('#mypopupmenu').is(':visible') ) {
        if (event.target.id != 'click_this_to_show_mypopupmenu') {
            $('#mypopupmenu').hide();
        }
    }
});

// Listen to selector's clicks
$('#click_this_to_show_mypopupmenu').click(function() {

  // If the menu is visible, and you clicked the selector again we need to hide
  if ( $('#mypopupmenu').is(':visible') {
      $('#mypopupmenu').hide();
      return true;
  }

  // Else we need to show the popup menu
  $('#mypopupmenu').show();
});

其他回答

您不需要(很多)JavaScript,只需要选择器内的:focus:

使用侧边栏:集中在显示侧边栏。在侧边栏和正文元素上设置tabindex=-1,使其可聚焦。使用sidbarEl.focus()和document.body.focus)设置侧边栏的可见性。

const menuButton=document.querySelector('.menu button');const sidebard=document.querySelector('.sidebard');menuButton.onmousedown=ev=>{ev.prpreventDefault();(边栏.包含(document.activeElement)?document.body:侧边栏).focus();};*{框大小调整:边框;}.侧边栏{位置:固定;宽度:15em;左:-15em;顶部:0;底部:0;过渡:左0.3s缓进缓出;背景色:#eef;衬垫:3em 1em;}侧边栏:焦点在{左:0;}.侧边栏:焦点{大纲:0;}.菜单按钮{位置:固定;顶部:0;左:0;填充:1em;背景色:#eef;边框:0;}正文{最大宽度:30em;边距:3em;}<body tabindex='-1'><nav class='sidebar'tabindex='-1'>提要栏内容<input-type=“text”/></nav><button class=“菜单按钮”>☰</按钮>身体内容在这里,Lorem ipsum坐amet等</body>

使用流中断、模糊/聚焦事件或任何其他棘手的技术,只需将事件流与元素的亲属关系匹配即可:

$(document).on("click.menu-outside", function(event){
    // Test if target and it's parent aren't #menuscontainer
    // That means the click event occur on other branch of document tree
    if(!$(event.target).parents().andSelf().is("#menuscontainer")){
        // Click outisde #menuscontainer
        // Hide the menus (but test if menus aren't already hidden)
    }
});

要删除事件侦听器外部的单击,只需执行以下操作:

$(document).off("click.menu-outside");

这对我来说非常有效!!

$('html').click(function (e) {
    if (e.target.id == 'YOUR-DIV-ID') {
        //do something
    } else {
        //do something
    }
});
$("body > div:not(#dvid)").click(function (e) {
    //your code
}); 

这是我解决这个问题的方法:

$(document).ready(function() {
  $('#user-toggle').click(function(e) {
    $('#user-nav').toggle();
    e.stopPropagation();
  });

  $('body').click(function() {
    $('#user-nav').hide(); 
  });

  $('#user-nav').click(function(e){
    e.stopPropagation();
  });
});