首页 > 解决方案 > 如何通过点击外部关闭导航栏?

问题描述

我有一个带有 Bootstrap 3.3.7 主题的 Drupal 8.6.8 站点

当我点击外部时,我希望我的导航菜单关闭。我尝试了代码:

(function ($) {
  'use strict';

  $(document).click(function (event) {
    if (!$(event.target).closest('#navbar-collapse-first').length) {
      $('.navbar-collapse-first').collapse('hide');
    }
  });

  $(document).click(function (event) {
    if (!$(event.target).closest('#navbar-collapse-second').length) {
      $('.navbar-collapse-second').collapse('hide');
    }
  });

}(jQuery));

https://css-tricks.com/dangers-stopping-event-propagation/

它不起作用,如果我在导航菜单之外单击,它不起作用 此代码仅在我删除第二个或离开第二个并删除第一个时才有效。

如何在 2 菜单上应用这个?

更新 :

我找到了答案:

(function ($) {
  'use strict';

  $(document).click(function (event) {
    if (!$(event.target).closest('#navbar-collapse-first').length) {
      $('.navbar-collapse-first').collapse('hide');
    }
    if (!$(event.target).closest('#navbar-collapse-second').length) {
      $('.navbar-collapse-second').collapse('hide');
    }
  });

}(jQuery));

标签: javascriptjquerytwitter-bootstrapnavigationcollapse

解决方案


您可以使用此功能

function OnwindowClick(elem , action){
    $(document).on('click',function(e){
        if (!$(elem).is(e.target) // if the target of the click isn't the container...
            && $(elem).has(e.target).length === 0) // ... nor a descendant of the container
        {
            action();
        }
    });
}

并像使用它一样

// OnwindowClick(elem , action) add the prevent elements in `elem` something like this
OnwindowClick('#navbar-collapse-first , #navbar-collapse-second', function(){
   $('.navbar-collapse-first, .navbar-collapse-second').collapse('hide');
});

笔记:

  • 无需.closest()直接使用选择器

  • elem是防止文档点击它的元素

附加:您仍然需要将按钮添加到elem..#navbar-collapse-first , #navbar-collapse-second , button1_Selector , button2_Selector

如何使用此功能的示例

$(document).ready(function(){
  $('button.clickable').on('click' , function(){
    $(this).text($(this).text() == 'Like' ? 'Dislike' : 'Like');
  });
  
  OnwindowClick('button.clickable' , function(){
    $('button.clickable').fadeOut(400);
    setTimeout(function(){
      $('button.clickable').fadeIn(400);
    } , 5000);
  });
});


function OnwindowClick(elem , action){
    $(document).on('click',function(e){
        if (!$(elem).is(e.target) // if the target of the click isn't the container...
            && $(elem).has(e.target).length === 0) // ... nor a descendant of the container
        {
            action();
        }
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="clickable">Like</button>


推荐阅读