jQuery Bootstrap,向下滚动后使导航栏粘滞?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17687172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:44:22  来源:igfitidea点击:

Bootstrap, make a navbar sticky after scrolling down?

javascriptjqueryhtmlcsstwitter-bootstrap

提问by user2441391

I have a navbar which is below the header image. I want the navbar to stick to the top of the webpage when I scroll down. I can't think of the jQuery or CSS required, because the navbar seems to stick right below the header image leaving some gap.

我有一个位于标题图像下方的导航栏。当我向下滚动时,我希望导航栏粘在网页的顶部。我想不出需要 jQuery 或 CSS,因为导航栏似乎贴在标题图像的正下方,留下了一些间隙。

<div class="headerwrap pull-center">
<div  class="container">
    <div id="header" class="row-fluid">
        <div class="span5" id="phones">
            <img class="phone" src="img/white.png" alt="">
        </div>
        <div class="span7" id="mm-logo">
            <img class="mm-log" src="img/logo.png" alt="">
        </div>
    </div>
</div>
</div>


<div class="navbar navbar-inner" id="border-stuff">
    <div class="span12">

        <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>

<!-- Everything you want hidden at 768px or less, place within here -->
<div class="nav-collapse collapse" id="center-nav">
<ul class="nav" >
    <li><a href="#h1"><h3>Heading1</h3></a></li><li class="divider-vertical"></li>
    <li><a href="#h2"><h3>Heading2</h3></a></li><li      class="divider-vertical"></li>
    <li><a href="#h3"><h3>Heading3</h3></a></li><li class="divider-vertical">  </li>
    <li><a href="#h4"><h3>Heading4</h3></a></li><li class="divider-vertical"></li>
    <li><a href="#h5"><h3>Heading4</h3></a></li>
</ul>
</div>

</div>
</div>

回答by Nathan Breit

If you want your navbar to stay fixed at the top of the screen only once the header image has scrolled away you can use the bootstrap affix plugin.

如果您希望导航栏仅在标题图像滚动后才固定在屏幕顶部,您可以使用引导词缀插件

回答by Henrique

You just need to replace your Jquery code to this:

您只需要将您的 Jquery 代码替换为:

$('#sidebar').affix({
  offset: {
    top: 50
  }
});

And adjust the top to whatever fits best.

并将顶部调整到最合适的位置。