单击其他菜单时,如何关闭展开的菜单

时间:2016-12-16 01:59:48

标签: javascript jquery

菜单有切换菜单但是当我点击其他菜单时它不会关闭并保持打开状态。当我点击其他菜单时,我需要关闭扩展菜单。



<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<nav>
  <ul class="nav">
    <li><a data-toggle="collapse in" data-parent="#accordion" href="#">Link 1</a>
    </li>
    <li><a href="#" id="btn-1" data-toggle="collapse" data-target="#submenu1" aria-expanded="false">Link 2 (toggle)</a>
      <ul class="nav collapse" id="submenu1" role="menu" aria-labelledby="btn-1">
        <li><a href="#">Link 2.1</a>
        </li>
        <li><a href="#">Link 2.2</a>
        </li>
        <li><a href="#">Link 2.3</a>
        </li>
      </ul>
    </li>
    <li><a href="#">Link 3</a>
    </li>
    <li><a href="#">Link 4</a>
    </li>
  </ul>
</nav>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您可以参考此代码:

$(document).ready(function () {
    $(document).click(function (event) {
        var clickover = $(event.target);
        var _opened = $(".navbar-collapse").hasClass("navbar-collapse in");
        if (_opened === true && !clickover.hasClass("navbar-toggle")) {
            $("button.navbar-toggle").click();
        }
    });
});