Bootstrap 3折叠菜单不关闭点击

[英]Bootstrap 3 collapsed menu doesn't close on click


I have a more or less standard navigation from bootstrap 3

我有一个或多或少的标准导航从引导3

<body data-spy="scroll" data-target=".navbar-collapse">
    <!-- ---------- Navigation ---------- -->
    <div class="navbar navbar-fixed-top" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                </button>
                <a class="navbar-brand" href="index.html"> <img src="#"></a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li class="active"><a href="#home">Home</a></li>
                    <li><a href="#one">One</a></li>
                    <li><a href="#two">Two</a></li>
                    <li><a href="#three">Three</a></li>
                    <li><a href="#four">Four</a></li>
                </ul>
            </div>
        </div>
    </div>

It collapses normally on smaller devices. Clicking on the menu button expands the menu but if I click (or touch for that matter) on a menu link, the menu stays open. What do I have to do, to close it again?

它通常在较小的设备上崩溃。单击“菜单”按钮会展开菜单,但如果我在“菜单”链接上单击(或单击),菜单就会保持打开状态。我该怎么做,再把它关上?

23 个解决方案

#1


41  

Bootstrap's default setting is to keep the menu open when you click on a menu item. You can manually override this behaviour by calling .collapse('hide'); on the jQuery element that you want to collapse.

Bootstrap的默认设置是在单击菜单项时保持菜单打开。您可以通过调用.崩溃('hide')手动重写此行为;在要折叠的jQuery元素上。

#2


124  

Just to share this from solutions on GitHub, this was the popular answer:

为了分享GitHub上的解决方案,以下是最流行的答案:

https://github.com/twbs/bootstrap/issues/9013#issuecomment-39698247

https://github.com/twbs/bootstrap/issues/9013 # issuecomment - 39698247

$(document).on('click','.navbar-collapse.in',function(e) {
    if( $(e.target).is('a') ) {
        $(this).collapse('hide');
    }
});

This is wired to the document, so you don't have to do it on ready() (you can dynamically append links to your menu and it will still work), and it only gets called if the menu is already expanded. Some people have reported weird flashing where the menu opens and then immediately closes with other code that did not verify that the menu had the "in" class.

这是与文档连接的,所以您不必在ready()上完成它(您可以动态地将链接添加到菜单中,它仍然会工作),并且只有在菜单已经扩展时才会调用它。有些人报告说,在菜单打开的地方会出现奇怪的闪烁,然后立即用其他代码关闭,这些代码没有验证菜单是否有“in”类。

[UPDATE 2014-11-04] apparently when using sub-menus, the above can cause problems, so the above got modified to:

[更新2014-11-04]显然在使用子菜单时,上面的内容会导致问题,因此将上面的内容修改为:

$(document).on('click','.navbar-collapse.in',function(e) {
    if( $(e.target).is('a:not(".dropdown-toggle")') ) {
        $(this).collapse('hide');
    }
});

#3


113  

Change this:

改变:

<li><a href="#one">One</a></li>

to this:

:

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

This simple change worked for me.

这个简单的改变对我起作用了。

Ref: https://github.com/twbs/bootstrap/issues/9013

裁判:https://github.com/twbs/bootstrap/issues/9013

#4


44  

I had the same problem but caused by including twice bootstrap.js and jquery.js files.

我也遇到了同样的问题,但是由于包含了两次bootstrap。js和jquery。js文件。

On a single click the event was processed twice by both jquery instances. One closed and one opened the toggle.

一次单击事件被两个jquery实例处理两次。一个关上,一个打开开关。

#5


11  

$(".navbar-nav li a").click(function(event) {
    if (!$(this).parent().hasClass('dropdown'))
        $(".navbar-collapse").collapse('hide');
});

This would help in handling drop down in nav bar

这将有助于处理在导航条下降

#6


9  

I am having/had similar issues with Bootstrap 4, alpha-6, and Joakim Johanssons answer above started me in the right direction. No javascript required. Putting data-target=".navbar-collapse" and data-toggle="collapse" into the div tag inside the nav, but surrounding the links/buttons, worked for me.

我在Bootstrap 4、alpha-6和上面Joakim johansson的回答让我走上了正确的方向。不需要javascript。把数据目标= "。navbar-崩溃和data-toggle="崩溃"进入了nav的div标签,但是围绕着链接/按钮,为我工作。

<div class="navbar-nav" data-target=".navbar-collapse" data-toggle="collapse">
   <a class="nav-item nav-link" href="#">Menu Item 1</a>
   ...
</div>

#7


5  

I had the same problem, I was using jQuery-1.7.1 and bootstrap 3.2.0. I changed my jQuery version to the latest (jquery-1.11.2) version and everything works well.

我遇到了同样的问题,我使用了jQuery-1.7.1和bootstrap 3.2.0。我将jQuery版本更改为最新版本(jQuery -1.11.2),一切都运行良好。

#8


4  

Though the solution posted earlier to change the menu item itself, like below, works when the menu is on a small device, it has a side effect when the menu is on full width and expanded, this can result in a horizontal scrollbar sliding over your menu items. The javascript solutions do not have this side-effect.

虽然之前发布的改变菜单项本身的解决方案(如下所示)在菜单位于小设备上时是有效的,但当菜单全宽并展开时,它会产生副作用,这可能导致水平滚动条在菜单项上滑动。javascript解决方案没有这种副作用。

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

(sorry for answering like this, wanted to add a comment to that answer, but, seems I haven't sufficient credit to make remarks )

(不好意思这样回答,我想补充一点意见,但是,我似乎没有足够的信用发表意见)

#9


4  

I did

我所做的

$(".navbar-toggle").click(function(event) {
    $(".navbar-collapse").toggle('in');
});

#10


3  

I know this question is for Bootstrap 3 but if you are looking solution for Bootstrap 4, just do this:

我知道这个问题是关于Bootstrap 3的,但是如果你正在寻找Bootstrap 4的解决方案,你可以这样做:

$(document).on('click','.navbar-collapse.show',function(e) {
  $(this).collapse('hide');
});

#11


1  

In case you want to manually override this behaviour by calling .collapse('hide') within an angular's directive, here is the code:

如果您想要在一个角的指令中通过调用.collapse(‘hide’)来手动重写这种行为,以下是代码:

javascript file:

javascript文件:

angular
  .module('yourAppModule')
  .directive('btnAutoCollapse', directive);

function directive() {
  var dir = {
    restrict: 'A',
    scope: {},
    link: link
  };
  return dir;

  function link(scope, element, attrs) {    
    element.on('click', function(event) {              
      $(".navbar-collapse.in").collapse('hide');
    });
  }
}

Html:

Html:

<li class="navbar-btn">
     <a href="#" ng-hide="username" **btn-auto-collapse**>Sign in</a>
</li>

#12


1  

If you only want your navigation to toggle when used on a mobile screen, just adding data-toggle="collapse" and data-target="#navbar" to your a elements will work on the mobile screen, but will give you a weird flicker when clicked on a desktop screen. The jQuery solutions do not work well if you are in an Aurelia or Angular environment.

如果你只希望你的导航在移动屏幕上使用时可以切换,那么只要在你的a元素中添加data-toggle=“折叠”和data-target=“#navbar”就可以在移动屏幕上工作,但是当你在桌面屏幕上点击时,它会给你一个奇怪的闪烁。如果您处于Aurelia或角环境中,jQuery解决方案就不会很好地工作。

The best solution for me was to create a custom attribute that listens to the corresponding media query and adds in the data-toggle="collapse"attribute if desired:

对于我来说,最好的解决方案是创建一个自定义属性,该属性可以侦听相应的媒体查询,并在需要时添加data-toggle=“崩溃”属性:

<a href="#" ... collapse-toggle-if-less768 data-target="#navbar"> ...

< a href = " # "……collapse-toggle-if-less768数据目标= " #导航" >…

The custom attribute with Aurelia looks like this:

Aurelia的自定义属性如下:

import {autoinject} from 'aurelia-framework';

@autoinject
export class CollapseToggleIfLess768CustomAttribute {
  element: Element;

  constructor(element: Element) {
    this.element = element;
    var mql = window.matchMedia("(min-width: 768px)");
    mql.addListener((mediaQueryList: MediaQueryList) => this.handleMediaChange(mediaQueryList));
    this.handleMediaChange(mql);
  }

  handleMediaChange(mediaQueryList: MediaQueryList) {
    if (mediaQueryList.matches) {
      var dataToggle = this.element.attributes.getNamedItem("data-toggle");
      if (dataToggle) {
        this.element.attributes.removeNamedItem("data-toggle");
      }
    } else {
      var dataToggle = this.element.attributes.getNamedItem("data-toggle");
      if (!dataToggle) {
        var dataToggle = document.createAttribute("data-toggle");
        dataToggle.value = "collapse";
        this.element.attributes.setNamedItem(dataToggle);
      }
    }
  }
}

#13


1  

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

#14


0  

I found that after much struggle, trial and error, the best solution for me on jsfiddle. Link to inspiration on jsfiddle.net. I am using bootstrap's navbar navbar-fixed-top with collapse and hamburger toggle. Here is my version on jsfiddle: jsfiddle Scrollspy navbar. I was only getting basic functionality using the instructions on getbootsrap.com. For me, the problem was mostly in the vague directions and js recommended by the getbootstrap site. The best part was that adding this extra bit of js (which does include some of what is mentioned in the above threads) solved several Scrollspy issues for me including:

经过多次的努力、尝试和错误,我发现在jsfiddle是最好的解决方案。链接到jsfiddle.net上的灵感。我使用的是bootstrap的navbar navbar-fixed-top,带有折叠和汉堡包切换功能。这是我在jsfiddle的版本:jsfiddle Scrollspy navbar。我只是使用getbootsrap.com上的说明获得基本的功能。对我来说,问题主要是由getbootstrap站点推荐的那些模糊的方向和js。最好的部分是,添加了这些额外的js(其中包含了上述线程中提到的一些内容),为我解决了几个Scrollspy问题,包括:

  1. Collapsed/toggled nav menu hides when nav "section" (e.g. href="#foobar") is clicked (issue addressing this thread).
  2. 当nav“section”(例如href="#foobar")被点击(问题处理该线程)时,导航菜单隐藏。
  3. Active "section" was successfully highlighted (ie. js successfully created class="active")
  4. 活动的“部分”被成功突出。js成功创建了类=“活跃”)
  5. Annoying vertical scroll bar found on collapsed nav (only on small screens) was eliminated.
  6. 在崩溃的导航(仅在小屏幕上)发现的令人讨厌的垂直滚动条被消除。

NOTE: In the js code shown below (from the second jsfiddle link in my post):

注意:在下面显示的js代码中(来自我文章中的第二个jsfiddle链接):

topMenu = $("#myScrollspy"),

topMenu = $(" # myScrollspy "),

...the value "myScrollspy" must match it the id="" in your HTML like so...

…值“myScrollspy”必须匹配它的id=""在你的HTML中这样…

<nav id="myScrollspy" class="navbar navbar-default navbar-fixed-top">

Of course you can change that value to whatever value you like.

当然,您可以将该值更改为您喜欢的任何值。

#15


0  

All you need is data-target=".navbar-collapse" in the button, nothing else.

您所需要的是data-target="。在按钮中,没有别的东西。

<button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".navbar-collapse">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
</button>

#16


0  

Please make sure You are using latest bootstrap js version. I was facing the same problem and just upgrading the bootstrap.js file from bootstrap-3.3.6 did the magic.

请确保您正在使用最新的bootstrap js版本。我也遇到了同样的问题,只是升级了引导程序。来自bootstrap-3.3.6的js文件发挥了神奇的作用。

#17


0  

This is the code that worked for me:

这是对我有用的代码:

jQuery('document').ready(function()
{   
   $(".navbar-header button").click(function(event) {
   if ($(".navbar-collapse").hasClass('in'))
   {  $(".navbar-collapse").slideUp();  }
});})

#18


0  

I had the same problem, ensure that bootstrap.js is included in your html page. In my case the menu opened but did not close. As soon as I included the bootstrap js file, everything just worked.

我也有同样的问题,确保引导。js包含在html页面中。在我的情况下,菜单打开了,但没有关闭。一旦我包含了bootstrap js文件,一切就正常了。

#19


0  

Simple Try to make a function in javascript for dropdown collapse class.

简单地尝试在javascript中为下拉式折叠类创建一个函数。

Example:

例子:

JS:

JS:

$scope.toogleMyClass  = function(){

    //dropdown-element

    $timeout(function(){
        $scope.preLoader = false;
        $(document).ready(function() {
            $("#dropdown-element").toggleClass('show');
        });
    },100);

};

Hook this function to onClick simple works for me.

将这个函数挂接到onClick simple works上。

#20


0  

I had the similar issue but mine wouldn't stay open it would open/close quickly, I found that I had jquery-1.11.1.min.js loading before bootstrap.min.js. So I reversed the order of those 2 files and fixed my menu. Runs flawlessly now. Hope it helps

我也遇到过类似的问题,但我的不会一直打开它会很快打开/关闭,我发现我有jquery1.11.1分钟。js bootstrap.min.js之前加载。所以我颠倒了这两个文件的顺序,修改了我的菜单。现在运行完美。希望它能帮助

#21


0  

The problem could be you are using out of date versions of bootstrap or jquery, OR you are calling more than one version in your markup.

问题可能是您正在使用过时的bootstrap或jquery版本,或者您正在标记中调用多个版本。

Just keep the latest versions, you only need the one reference. Solves the problem.

保持最新的版本,你只需要一个引用。解决问题。

#22


0  

you may want to just ensure you're loading your jQuery and Bootstrap.min.js ATF. Your navigation is the first thing to render on the page, so if you have your scripts in the bottom of your HTML, you're losing any JavaScript functionality.

您可能只想确保您正在加载jQuery和Bootstrap.min。js ATF。导航是页面上要呈现的第一件事,所以如果在HTML底部有脚本,就会丢失任何JavaScript功能。

#23


-2  

My menu is not a navbar standard one, but i managed to auto collapse mine, using an "onclick" function and a ".click()".

我的菜单不是一个导航条标准的菜单,但是我使用了“onclick”函数和“.click()”函数自动折叠我的菜单。

<div class="main-header">
    <div class="container">
        <div id="menu-wrapper">
            <div class="row">

                <div class="logo-wrapper col-lg-4 col-md-6 col-sm-7 hidden-xs">

                </div> <!-- /.logo-wrapper -->

                <div class="logo-wrapper2 visible-xs col-xs-9">

                </div> <!-- /.smaller logo-wrapper -->

                <div class="col-lg-8 col-md-6 col-sm-5 col-xs-3 main-menu text-center">
                    <ul class="menu-first hidden-md hidden-sm hidden-xs">
                        <li class="active"><a href="#">item1</a></li> |
                        <li><a href="#our-team">item2</a></li> |
                        <li><a href="#services">item3</a></li> |
                        <li><a href="#elia">item4</a></li> |
                        <li><a href="#portfolio">item5</a></li> |
                        <li><a href="#contact">item6</a></li>
                    </ul>
                    <a href="#" class="toggle-menu visible-md visible-sm visible-xs"><i class="fa fa-bars"></i></a>
                </div> <!-- /.main-menu -->
            </div> <!-- /.row -->
        </div> <!-- /#menu-wrapper -->
        <div class="menu-responsive hidden-lg">
            <ul>
                <li class="active" onclick = $(".toggle-menu").click();><a href="#">item1</a></li>
                <li><a href="#our-team" onclick = $(".toggle-menu").click();>item2</a></li>
                <li><a href="#services" onclick = $(".toggle-menu").click();>item3</a></li>
                <li><a href="#elia" onclick = $(".toggle-menu").click();>item4</a></li>
                <li><a href="#portfolio" onclick = $(".toggle-menu").click();>item5</a></li>
                <li><a href="#contact" onclick = $(".toggle-menu").click();>item6</a></li>
            </ul>
        </div> <!-- /.menu-responsive -->
    </div> <!-- /.container -->
</div> <!-- /.main-header 

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/01/18/18ac4e4dc3b113f4a6eafc8c55c959f3.html



 
  © 2014-2022 ITdaan.com 联系我们: