Jquery: drop down menu wont disappear after clicking outside of menu

后端 未结 4 676
盖世英雄少女心
盖世英雄少女心 2020-12-30 17:02

I\'m new to jquery and I\'m looking at google\'s code to create their \'More\' button. I\'ve got it working atm but the only way to make the drop down disappear is to click

相关标签:
4条回答
  • 2020-12-30 17:08

    Rather than testing every click on the html dom element you could bind a blur event to the specific menu item when you make it active to then switch it off when the blur event is fired. Replace these few lines:

      //displaying the drop down menu
      $(this).parent().parent().find('.active').removeClass('active');
      $(this).parent().addClass('active');
    

    with these:

      //displaying the drop down menu
      $('.active').removeClass('active');
      $(this).parent().addClass('active');
      $(this).blur(function() {
          $('.active').removeClass('active');
      });
    
    0 讨论(0)
  • 2020-12-30 17:10

    Bind a click event to html to capture any click made, and make it hide the menu

    $("html").click(function() {
      menu.find('.active').removeClass('active');
    });
    

    Then override that on your menu's click event using .stopPropagation();

    menu.find('ul li > a').bind('click', function (event) {
      event.stopPropagation();
    

    Fiddle: http://jsfiddle.net/rKaPN/12/

    0 讨论(0)
  • 2020-12-30 17:23

    On opening of the menu, create a transparent overlay div of the same width and height of the window. On click of that div, close the menu and destroy the div.

    0 讨论(0)
  • 2020-12-30 17:26

    You could add this too , so the user don't have to click

    $("body:not(.menu)").hover(function(){ $(".menu").find('.active').removeClass('active');})
    
    0 讨论(0)
提交回复
热议问题