简体   繁体   English

Bootstrap 关闭响应式菜单“点击”

[英]Bootstrap close responsive menu "on click"

On "PRODUCTS" click I slide up a white div (as seen in attached).在“产品”上单击我向上滑动一个白色 div(如附件所示)。 When in responsive (mobile and tablet), I would like to automaticly close the responsive navbar and only show the white bar.在响应式(移动设备和平板电脑)中,我想自动关闭响应式导航栏并仅显示白色栏。

I tried:我试过:

$('.btn-navbar').click();  

also tried:也试过:

$('.nav-collapse').toggle();

And it does work.它确实有效。 However in desktop size, it is also called and does something funky to the menu where it shrinks for a second.然而,在桌面大小中,它也被称为并对菜单进行了一些时髦的操作,它会缩小一秒钟。

Any ideas?有任何想法吗?

在此处输入图片说明

You don't have to add any extra javascript to what's already included with bootstraps collapse option.您不必向已包含在引导程序折叠选项中的内容添加任何额外的 javascript。 Instead simply include data-toggle and data-target selectors on your menu list items just as you do with your navbar-toggle button.相反,只需在菜单列表项中包含数据切换和数据目标选择器,就像使用导航栏切换按钮一样。 So for your Products menu item it would look like this所以对于您的产品菜单项,它看起来像这样

<li><a href="#Products" data-toggle="collapse" data-target=".navbar-collapse">Products</a></li>

Then you would need to repeat the data-toggle and data-target selectors for each menu item然后您需要为每个菜单项重复数据切换和数据目标选择器

EDIT!!!编辑!!! In order to fix overflow issues and flickering on this fix I'm adding some more code that will fix this and still not have any extra javascript.为了修复溢出问题并在此修复程序上闪烁,我添加了更多代码来解决此问题,但仍然没有任何额外的 javascript。 Here is the new code:这是新代码:

<li><a href="#products" class="hidden-xs">Products</a></li>
<li><a href="#products" class="visible-xs" data-toggle="collapse" data-target=".navbar-collapse">Products</a></li>

Here it is at work http://jsfiddle.net/jaketaylor/84mqazgq/这是在工作http://jsfiddle.net/jaketaylor/84mqazgq/

This will make your toggle and target selectors specific to screen size and eliminate glitches on the larger menu.这将使您的切换和目标选择器特定于屏幕尺寸并消除较大菜单上的故障。 If anyone is still having issues with glitches please let me know and I'll find a fix.如果有人仍然遇到故障问题,请告诉我,我会找到解决方法。 Thanks谢谢

EDIT : In the bootstrap v4.1.3 I couldnt use visible/hidden classes.编辑:在引导程序 v4.1.3 中,我无法使用可见/隐藏类。 Instead of hidden-xs use d-none d-sm-block and instead of visible-xs use d-block d-sm-none .而不是hidden-xs使用d-none d-sm-block而不是visible-xs使用d-block d-sm-none

I've got it to work with animation!我已经让它与动画一起工作了!

Menu in html: html中的菜单:

<div id="nav-main" class="nav-collapse collapse">
     <ul class="nav">
         <li>
             <a href='#somewhere'>Somewhere</a>
         </li>
     </ul>
 </div>

Binding click event on all a elements in navigation to collapse menu (Bootstrap collapse plugin):将导航中所有元素的单击事件绑定到折叠菜单(Bootstrap 折叠插件):

 $(function(){ 
     var navMain = $("#nav-main");
     navMain.on("click", "a", null, function () {
         navMain.collapse('hide');
     });
 });

EDIT To make it more generic we can use following code snippet编辑为了使它更通用,我们可以使用以下代码片段

 $(function(){ 
     var navMain = $(".navbar-collapse"); // avoid dependency on #id
     // "a:not([data-toggle])" - to avoid issues caused
     // when you have dropdown inside navbar
     navMain.on("click", "a:not([data-toggle])", null, function () {
         navMain.collapse('hide');
     });
 });

I think you are all over engineering..我认为你是工程师。。

    $('.navbar-collapse ul li a').click(function(){ 
            $('.navbar-toggle:visible').click();
    });

EDIT: To take care of sub menus, make sure their toggle anchor has the dropdown-toggle class on it.编辑:要处理子菜单,请确保其切换锚具有下拉切换类。

    $(function () { 
            $('.navbar-collapse ul li a:not(.dropdown-toggle)').click(function () { 
                    $('.navbar-toggle:visible').click(); 
            }); 
    });

EDIT 2: Add support for phone touch.编辑 2:添加对手机触摸的支持。

    $(function () {
            $('.navbar-collapse ul li a:not(.dropdown-toggle)').bind('click touchstart', function () {
                    $('.navbar-toggle:visible').click();
            });
    });

I really liked Jake Taylor's idea of doing it without additional JavaScript and taking advantage of Bootstrap's collapse toggle.我真的很喜欢 Jake Taylor 的想法,即无需额外的 JavaScript 并利用 Bootstrap 的折叠切换。 I found you can fix the "flickering" issue present when the menu isn't in collapsed mode by modifying the data-target selector slightly to include the in class.我发现您可以通过稍微修改data-target选择器以包含in类来修复菜单未处于折叠模式时出现的“闪烁”问题。 So it looks like this:所以它看起来像这样:

<li><a href="#Products" data-toggle="collapse" data-target=".navbar-collapse.in">Products</a></li>

I didn't test it with nested dropdowns/menus, so YMMV.我没有用嵌套的下拉菜单/菜单测试它,所以 YMMV。

just to be complete, in Bootstrap 4.0.0-beta using .show worked for me...只是为了完成,在 Bootstrap 4.0.0-beta 中使用.show为我工作......

<li>
  <a href="#Products" data-toggle="collapse" data-target=".navbar-collapse.show">Products</a>
</li>

I'm assuming you have a line like this defining the nav area, based on Bootstrap examples and all我假设您有这样一行定义导航区域,基于 Bootstrap 示例和所有

<div class="nav-collapse collapse" >

Simply add the properties as such, like on the MENU button只需添加属性,就像在 MENU 按钮上一样

<div class="nav-collapse collapse" data-toggle="collapse"  data-target=".nav-collapse">

I've added to <body> as well, worked.我也添加到<body> ,成功了。 Can't say I've profiled it or anything, but seems a treat to me...until you click on a random spot of the UI to open the menu, so not so good that.不能说我已经描述了它或任何东西,但对我来说似乎是一种享受......直到你点击 UI 的一个随机位置来打开菜单,所以不是那么好。

DK DK

This works, but does not animate.这有效,但没有动画。

$('.btn-navbar').addClass('collapsed');
$('.nav-collapse').removeClass('in').css('height', '0');

In the HTML I added a class of nav-link to the a tag of each navigation link.在HTML我添加了一个类导航链接的每个导航链接的标签

$('.nav-link').click(
    function () {
        $('.navbar-collapse').removeClass('in');
    }
);

此解决方案在台式机和移动设备上都表现出色。

<div id="navbar" class="navbar-collapse collapse" data-toggle="collapse"  data-target=".navbar-collapse collapse">

Just to spell out user1040259's solution, add this code to your $(document).ready(function() {});只是为了说明 user1040259 的解决方案,将此代码添加到您的 $(document).ready(function() {});

    $('.nav').click( function() {
        $('.btn-navbar').addClass('collapsed');
        $('.nav-collapse').removeClass('in').css('height', '0');
    });

As they mention, this doesn't animate the move... but it does close the nav bar on item selection正如他们所提到的,这不会为移动设置动画......但它会关闭项目选择的导航栏

For those using AngularJS and Angular UI Router with this, here is my solution (using mollwe's toggle).对于那些使用 AngularJS 和 Angular UI Router 的人,这是我的解决方案(使用 mollwe 的切换)。 Where ".navbar-main-collapse" is my "data-target".其中“.navbar-main-collapse”是我的“数据目标”。

Create directive:创建指令:

module.directive('navbarMainCollapse', ['$rootScope', function ($rootScope) {
    return {
        restrict: 'C',
        link: function (scope, element) {
            //watch for state/route change (Angular UI Router specific)
            $rootScope.$on('$stateChangeSuccess', function () {
                if (!element.hasClass('collapse')) {
                    element.collapse('hide');
                }
            });
        }
    };
}]);

Use Directive:使用指令:

<div class="collapse navbar-collapse navbar-main-collapse">
    <your menu>

This should do the trick.这应该可以解决问题。

Requires bootstrap.js.需要 bootstrap.js。

Example => http://getbootstrap.com/javascript/#collapse示例 => http://getbootstrap.com/javascript/#collapse

    $('.nav li a').click(function() {
      $('#nav-main').collapse('hide');
    });

This does the same thing as adding 'data-toggle="collapse"' and 'href="yournavigationID"' attributes to navigation menus tags.这与将 'data-toggle="collapse"' 和 'href="yournavigationID"' 属性添加到导航菜单标签的作用相同。

I'm using the mollwe function, although I added 2 improvements:我正在使用 mollwe 函数,尽管我添加了 2 个改进:

a) Avoid the dropdown closing if the link clicked is collapsed (including other links) a) 如果单击的链接折叠(包括其他链接),请避免下拉关闭

b) Hide the dropdown too, if you are clicking the visible web content. b) 如果您单击可见的 Web 内容,也可以隐藏下拉列表。

jQuery.fn.exists = function() {
                  return this.length > 0;
              }

    $(function() {
                var navMain = $(".navbar-collapse");
                navMain.on("click", "a", null, function() {
                    if ($(this).attr("href") !== "#") {
                        navMain.collapse('hide');
                    }
                });

                $("#content").bind("click", function() {
                     if ($(".navbar-collapse.navbar-ex1-collapse.in").exists()) {
                        navMain.collapse('hide');
                    }
                });

            });

Not the newest thread but i searched for a solution for the same Problem and found one (a mix of some others).不是最新的线程,但我搜索了相同问题的解决方案并找到了一个(其他一些的混合)。

I gave the NavButton:我给了导航按钮:

<type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> ...

an id / Identifier like:一个 id / 标识符,如:

 <button id="navcop" type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

Not the finest "Idea" - but: Works for me!不是最好的“想法”——但是:对我有用! Now you can check up the visibility of your button (with jquery) like:现在您可以检查按钮的可见性(使用 jquery),例如:

 var target = $('#navcop');
   if(target.is(":visible")){
   $('#navcop').click();
   }

(NOTE: This is just a Code snipped ! I used a "onclick" Event on my Nav Links! (Starting a AJAX Reguest.) (注意:这只是一个代码片段!我在我的导航链接上使用了“onclick”事件!(启动 AJAX 请求。)

The result is: If the Button is "visible" it got "clicked" ... So: No Bug if you use the "Fullscreen view" of Bootstrap (width of over 940px).结果是:如果按钮是“可见的”,它就会被“点击”......所以:如果您使用 Bootstrap 的“全屏视图”(宽度超过 940 像素),则没有错误。

Greetings Ralph问候拉尔夫

PS: It works fine with IE9, IE10 and Firefox 25. Didnt checked up others - But i can't see a Problem :-) PS:它适用于 IE9、IE10 和 Firefox 25。没有检查其他人 - 但我看不出问题:-)

This worked for me.这对我有用。 I have done like, when i click on the menu button, im adding or removing the class 'in' because by adding or removing that class the toggle is working by default.我已经这样做了,当我点击菜单按钮时,我添加或删除了“in”类,因为通过添加或删除该类,默认情况下切换是有效的。 'e.stopPropagation()' is to stop the default animation by bootstrap(i guess) you can also use the 'toggleClass' in place of add or remove class. 'e.stopPropagation()' 是通过引导程序停止默认动画(我猜)你也可以使用 'toggleClass' 代替添加或删除类。

$('#ChangeToggle').on('click', function (e) { $('#ChangeToggle').on('click', function (e) {

        if ($('.navbar-collapse').hasClass('in')) {
            $('.navbar-collapse').removeClass('in');
            e.stopPropagation();
        } else {
            $('.navbar-collapse').addClass('in');
            $('.navbar-collapse').collapse();
        }

    });

You cau use你可以使用

ul.nav {
    display: none;
}

This will by default close the navbar.这将默认关闭导航栏。 Please let me know anybody finds this usefull请让我知道有人觉得这很有用

If for example your toggle-able icon is visible only for extra small devices, then you could do something like this:例如,如果您的可切换图标仅对超小型设备可见,那么您可以执行以下操作:

$('[data-toggle="offcanvas"]').click(function () {
    $('#side-menu').toggleClass('hidden-xs');
});

Clicking [data-toggle="offcanvas"] will add bootstrap's .hidden-xs to my #side-menu which will hide the side-menu content, but will become visible again if you increase the window size.单击 [data-toggle="offcanvas"] 会将引导程序的 .hidden-xs 添加到我的 #side-menu 中,这将隐藏侧菜单内容,但如果增加窗口大小,它将再次可见。

if menu html is如果菜单 html 是

<div id="nav-main" class="nav-collapse collapse">
     <ul class="nav">
         <li>
             <a href='#somewhere'>Somewhere</a>
         </li>
     </ul>
</div>

on nav toggle 'in' class is added and removed from the toggle.在导航切换“in”类中添加和删除切换。 check if responsive menu is opened then perform the close toggle.检查响应式菜单是否打开,然后执行关闭切换。

$('.nav-collapse .nav a').on('click', function(){
    if ( $( '.nav-collapse' ).hasClass('in') ) {
        $('.navbar-toggle').click();
    }
});

Tuggle Nav Close, IE browser compatible answer, without any console error. Tuggle Nav Close,IE 浏览器兼容答案,没有任何控制台错误。 If you are using bootstrap, use this如果您使用引导程序,请使用此

$('.nav li a').on('click', function () {
    if ($("#navbar").hasClass("in")) {
        $('.navbar-collapse.in').show();
    }
    else {
        $('.navbar-collapse.in').hide();
    }
})

Bootstrap 4 solution without any Javascript没有任何 Javascript 的 Bootstrap 4 解决方案

Add attributes data-toggle="collapse" data-target="#navbarSupportedContent.show" to the div <div class="collapse navbar-collapse">将属性data-toggle="collapse" data-target="#navbarSupportedContent.show"到 div <div class="collapse navbar-collapse">

Make sure you provide the correct id in data-target确保在data-target提供正确的id

<div className="collapse navbar-collapse" id="navbarSupportedContent" data-toggle="collapse" data-target="#navbarSupportedContent.show">

.show is to avoid menu flickering in large resolutions .show是为了避免菜单在大分辨率下闪烁

 <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent" data-toggle="collapse" data-target="#navbarSupportedContent.show"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav>

I found an easy solution for this.我找到了一个简单的解决方案。 Just add the toggle code of the button on the navbar links too.只需在导航栏链接上添加按钮的切换代码。 In the below example is the code data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" .在下面的示例中是代码data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02"

This will close the menu when clicked and follow the link这将在单击时关闭菜单并点击链接

    <!--data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" from toggle button --> 
           <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
    
            <div class="collapse navbar-collapse nav-format-mobile" id="navbarTogglerDemo02">
              <ul class="navbar-nav ms-auto mb-2 mb-lg-0"> <!--https://stackoverflow.com/a/65365121/5763690-->
                <li class="nav-item">

<!--data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" from toggle button to nav item --> 
                  <a class="nav-link" aria-current="page" [routerLink]="'about'" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">About</a>
                </li>
                <li class="nav-item dropdown">
                  <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                    Services
                  </a>
                  <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <li><a class="dropdown-item" [routerLink]="'services'" fragment="why-us" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">Overview</a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item" [routerLink]="'services'" fragment="project" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">For companies</a></li>
                    <li><a class="dropdown-item" [routerLink]="'services'" fragment="startups" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">For Startups</a></li>
                    <li><a class="dropdown-item" [routerLink]="'/services'" fragment="ngos" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">For NGOs</a></li>
                  </ul>
                </li>
                <li class="nav-item">
<!--data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" from toggle button to nav item --> 
                  <a class="nav-link" [routerLink]="'products'" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">Products</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" [routerLink]="'career'" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">Career</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" [routerLink]="'contact'" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">Contact</a>
                </li>
              </ul>
            </div>

I tried the other suggestions in my Vue.js 3 app, however my vue-router router-links wouldn't work anymore.我在我的 Vue.js 3 应用程序中尝试了其他建议,但是我的 vue-router 路由器链接不再起作用。

I created a small function to click the menu toggle, if the menu had the "show" class.如果菜单具有“显示”类,我创建了一个小函数来单击菜单切换。 This worked great for me in all cases.这在所有情况下都对我很有用。

<template>
...
<div
    id="navbarNavigation"
    class="collapse navbar-collapse"
  >
    <ul
      class="navbar-nav me-auto mb-2 mb-lg-0"
    >
      <li class="nav-item">
        <router-link
          :to="route.url"
          class="nav-link"
          @click="closeMenu('navbarNavigation')"
        >
          My route name
        </router-link>
      </li>
    </ul>
  </div>
...
</template>

<script>
setup (props) {
    const closeMenu = (id) => {
      const menuShown = document.getElementById(id).classList.contains('show')
      if (menuShown) {
        const menuToggle = document.getElementsByClassName('navbar-toggler')[0]
        menuToggle.click()
      }
    }

    return { closeMenu }
  }
</script>
$('.navbar-toggle').trigger('click');

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

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