简体   繁体   中英

Click outside to close dropdown only works when click outside <nav>

The following nav I'm building works just fine, however I noticed that when click outside the nav buttons but still inside <nav> container the open dropdown doesn't close as it should however it does close when click outside <nav> . How can that be? Thank you for your help.

See Demo here

JQuery

$(document).ready(function() {
  $(".click").on("click", function(e) {
    var menu = $(this);
    toggleDropDown(menu);
  });

  $(document).on('mouseup',function(e) {
    var container = $("nav");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) {
      $('a.active').parent().find('.showup').stop(true, true).slideUp(500, function() {
        $(".main-container").removeClass("black-bg");
        if ($('a.active').hasClass('active')) {
          $('a.active').removeClass('active');
        }
      });
    }
  });

});


function toggleDropDown(menu) {
  var isActive = $('a.active').length;
  $('a.active').parent().find('.showup').stop(true, true).slideUp(500, function() {
    $(".main-container").removeClass("black-bg");
    if (menu.hasClass('active')) {
      menu.removeClass('active');
    } else {
      $('a.active').removeClass('active');
      menu.addClass('active');
      menu.parent().find('.showup').stop(true, true).slideDown(500, function() {
        $(".main-container").addClass("black-bg");
      });
    }
  });
  if (!isActive) {
    menu.addClass('active');
    menu.parent().find('.showup').stop(true, true).slideDown(500, function() {
      $(".main-container").addClass("black-bg");
    });
  }
}

您必须更改容器,例如:

var container = $("nav .top-bar-section ul");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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