简体   繁体   English

如何通过在打开按钮区域之外单击来关闭菜单?

[英]How to close a menu by clicking outside the area of the open button?

A menu opens when a specific button is clicked #btn . 单击特定按钮#btn时将打开一个菜单。

I would like to have the menu close, by also clicking outside the button. 我也想关闭菜单,方法是同时单击按钮外部。

Here is the FIDDLE: https://jsfiddle.net/maryisdead/rkapkoLu/ 这是FIDDLE: https ://jsfiddle.net/maryisdead/rkapkoLu/

Is this possible? 这可能吗?

Here is the javascript: 这是JavaScript:

(function() {
  var btn       = $('#btn');
  menu      = $('nav ul');
  menuHeight    = menu.height();

  $(btn).on('click', function(e) {
    e.preventDefault();
    menu.slideToggle();
  });

  $(window).resize(function(){
    var w = $(window).width();
    if(w > 320 && menu.is(':hidden')) {
      menu.removeAttr('style');
    }
  });
});

You literally want to have action after clicking on something that is not #btn button. 从字面上看,您希望在单击非#btn按钮之后执行操作。

$( document ).ready(function(){
  $('body *').not('#btn').click(function(){
     e.preventDefault();
     menu.slideToggle();
  })
});

Do not forget to unattach the event afterwards. 不要忘记以后取消附加活动。

You can simply set listener on body 您可以简单地在身上设置监听器

        $(".image").on('click', function(e) {
            e.preventDefault();
            menu.slideToggle();
        });

Do this 做这个

    $('html').click(function() {
menu.slideUp();
});

$('.nav-wrapper').click(function(event){
    event.stopPropagation();
});

use onblur event. 使用onblur事件。 It is the opposite of onfocus and is fired when the element loses the focus 它与onfocus相反,当元素失去焦点时会触发

onblur

I would HIGHLY recommend jQuery outsideevents http://benalman.com/projects/jquery-outside-events-plugin/ 我强烈建议jQuery outsideevents http://benalman.com/projects/jquery-outside-events-plugin/

$(btn).bind("clickoutside", function(event){ // Code to hide your menu. });

It does all the work of finding everything that's "not the button" for you. 它会为您查找“不是按钮”的所有内容。

I should also mention it does a lot more than clickoutside, like you could check if they focusoutside too so if they use tab shortcuts to navigate the page the menu still closes, etc. 我还要提到的是,它的功能远不止clickoutside,就像您可以检查它们是否也聚焦在外部,因此,如果他们使用选项卡快捷方式导航菜单仍关闭的页面,等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM