滚动后固定引导导航栏

时间:2015-05-16 10:35:48

标签: jquery html css twitter-bootstrap

以下是导航的html代码:

<div class="container">
    <nav class="navbar navbar-sm">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a href="#" class="navbar-brand"><i class="fa fa-home fa-lg"></i></a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li class="dropdown">
                    <a href="javascript:void(0)" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Services <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li class="dropdown-submenu">
                            <a href="javascript:void(0)">Rent A Plant</a>
                            <ul class="dropdown-menu">
                                <li><a href="javascript:void(0)">Why Indoor Plants</a></li>
                                <li><a href="javascript:void(0)">F.A.Q's</a></li>
                            </ul>
                        </li>
                        <li><a href="javascript:void(0)">Garden Maintenance</a></li>
                        <li><a href="javascript:void(0)">Vertical Gardens</a></li>
                        <li><a href="javascript:void(0)">Artificial Lawns</a></li>
                        <li><a href="javascript:void(0)">Garden Center</a></li>
                    </ul>
                </li>
                <li><a href="javascript:void(0)">Image Gallery</a></li>
                <li><a href="{{ url('/store') }}" style="background: #916649">E-Store</a></li>
            </ul>
        </div>
    </nav>
</div>

在导航上方,我有height: 100width: 200

的徽标

因此,向下滚动约130.我想让导航栏成为修复。所以我用它作为我的jQuery

$(window).bind('scroll', function() {
    var navHeight = 130; // custom nav height
    ($(window).scrollTop() > navHeight) ? 
        $('nav').addClass('navbar-fixed-top') :
        $('nav').removeClass('navbar-fixed-top');
});

这完全没问题。但导航栏的长度变为全长,我不想要。我希望它应该保持原样。我指的是固定长度。

我如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

您必须对nav元素应用固定宽度。当您希望它在页面上居中时,还要将左右边距设置为auto

nav {
  width: 100%;
  margin: 0 auto;
}

@media (min-width: 768px) {
    nav { width: 750px; }
}

@media (min-width: 992px) {
    nav { width: 970px; }
}

@media (min-width: 1200px) {
    nav { width: 1170px; }
}