简体   繁体   English

单击外部以关闭下拉菜单仅在单击外部时有效<nav>

[英]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> . 我正在构建的以下导航工作正常,但是我注意到,当在导航按钮外部单击但仍在<nav>容器中单击时,打开下拉菜单不会关闭,但应在<nav>外部单击时关闭。 How can that be? 怎么可能? Thank you for your help. 谢谢您的帮助。

See Demo here 在这里查看演示

JQuery 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");

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

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