当在按钮外单击时,如何在我的菜单中关闭动画折叠

时间:2014-01-23 15:40:01

标签: javascript jquery html css twitter-bootstrap-3

我的导航栏是这样的:

http://jsfiddle.net/Hg4Ts/3/

我的HTML代码:

<div class="wrapper">
    <div class="navbar navbar-default" role="navigation">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" 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>
          <a class="navbar-brand" href="#">Project name</a>
        </div>
        <div class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
              <ul class="dropdown-menu">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li class="divider"></li>
                <li class="dropdown-header">Nav header</li>
                <li><a href="#">Separated link</a></li>
                <li><a href="#">One more separated link</a></li>
              </ul>
            </li>
          </ul>
          <ul class="nav navbar-nav navbar-right">
            <li class="active"><a href="./">Default</a></li>
            <li><a href="../navbar-static-top/">Static top</a></li>
            <li><a href="../navbar-fixed-top/">Fixed top</a></li>
          </ul>
        </div><!--/.nav-collapse -->
    </div>
</div>

我的javascript代码:

$(document).ready(function () {
    function CloseNav() {
        $(".navbar-collapse").stop().css({ 'height': '1px' }).removeClass('in').addClass("collapse");
        $(".navbar-toggle").stop().removeClass('collapsed');
    }

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

    });
});

当在按钮外单击时,如何在我的菜单中关闭动画折叠。单击按钮外部时关闭但没有动画效果。如何在折叠打开时菜单按钮改变颜色?

1 个答案:

答案 0 :(得分:0)

此解决方案可能适合您。将CloseNav()函数切换到下面:

    function CloseNav() {
        $(".navbar-collapse").stop().animate({'height': 0},300, function () {
            $('.navbar-collapse').removeClass('in').addClass("collapse");
        });
        $(".navbar-toggle").stop().removeClass('collapsed');
    };

看起来只需将.collapse类添加到导航栏就可以立即切换高度。如果您制作动画然后添加该类,则会创建所需的上滑效果。

<强> fiddle demo