如何通过点击外,关闭导航栏?

问题描述 投票:0回答:2

我有一个Drupal 8.6.8现场与引导3.3.7主题

我希望我的导航菜单,关闭,当我点击之外。我试着用的代码:

(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));
javascript jquery twitter-bootstrap navigation collapse
2个回答
1
投票

您可以使用此功能

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>

0
投票

具有u试过这样:


    $(document).click(function (event) {
    if (!$(event.target).closest('#navbar-collapse-second, #navbar-collapse-second').length) {
      $('.navbar-collapse-second, .navbar-collapse-second').collapse('hide');
    }
  });
© www.soinside.com 2019 - 2024. All rights reserved.