如何创建一个粘性导航栏,在滚动后固定在顶部

41

我正在尝试制作一个导航栏,当网站首次加载时,它会出现在可视页面的底部,然后随着用户向下滚动,导航栏会向上滚动,并最终固定在顶部。我正在使用 Bootstrap,就像这个网站一样,但我不知道这个网站是如何做到的。 有什么帮助吗?

这是我想模仿的带有导航栏的网站:http://www.blastprocessor.co.uk/

这是我的导航 HTML 和 CSS 代码:

HTML:

<div class="navbar navbar-fixed-top" id="navbar">
    <div class="navbar-inner">
        <div class="container">
            <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>
            <div class="nav-collapse">
                <ul class="nav nav-pills">
                    <li class="active"><a href="#home">Home</a></li>
                    <li><a href="#service-link">Services</a></li>
                    <li><a href="#contact-link">Contact</a></li>
                </ul><!-- /.nav -->
            </div><!--/.nav-collapse -->
        </div><!-- /.container -->
    </div><!-- /.navbar-inner -->
</div><!-- /.navbar -->

这是我的CSS:

.navbar-fixed-top,.navbar-fixed-bottom{position:fixed; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none;}
.navbar .nav > li a{
    color:white; background:rgba(0,0,0,0.2); text-shadow:none; font-size:1.7em; font-family: marvel, serif; padding:.5em 1.3em; margin:1em 2em;
}
.navbar .nav > .active a:hover, .navbar .nav > li a:hover, .navbar .nav > .active a {
    color:white; ; background:#F90; text-shadow:none; font-size:1.7em; font-family: marvel, serif; padding:.5em 1.3em; margin:1em 2em;
}
.navbar .nav > li {padding:2em;}
.navbar.navbar-fixed-top .navbar-inner{background: rgba(255, 255, 255, 0);}
.navbar .nav, .navbar .nav > li {
    float:none;
    display:inline-block;
    *display:inline; /* ie7 fix */
    *zoom:1; /* hasLayout ie7 trigger */
    vertical-align: top;
    padding:0 2em;
}
.navbar-inner {text-align:center;}
.navbar .navbar-inner, .navbar .navbar-inner {border: none; box-shadow: none; filter: none;}
10个回答

41

我也在寻找同样的东西。我曾经看到过在Bootstrap 3.0中有这个功能,但是实际上我无法成功实现。这就是我想出来的方法,它非常简单使用jQuery和Javascript。

这里有JSFiddle可以进行演示...http://jsfiddle.net/CriddleCraddle/Wj9dD/

这个解决方案与网上和StackOverflow上的其他解决方案非常相似。如果您觉得这个不太有用,那就继续搜索您需要的东西吧。祝你好运!

这是HTML代码...

<div id="banner">
  <h2>put what you want here</h2>
  <p>just adjust javascript size to match this window</p>
</div>

  <nav id='nav_bar'>
    <ul class='nav_links'>
      <li><a href="url">Sign In</a></li>
      <li><a href="url">Blog</a></li>
      <li><a href="url">About</a></li>
    </ul>
  </nav>

<div id='body_div'>
  <p style='margin: 0; padding-top: 50px;'>and more stuff to continue scrolling here</p>
</div>

以下是 CSS 的代码...

html, body {
  height: 4000px;
}

.navbar-fixed {
  top: 0;
  z-index: 100;
  position: fixed;
  width: 100%;
}

#body_div {
  top: 0;
  position: relative;
  height: 200px;
  background-color: green;
}

#banner {
  width: 100%;
  height: 273px;
  background-color: gray;
  overflow: hidden;
}

#nav_bar {
  border: 0;
  background-color: #202020;
  border-radius: 0px;
  margin-bottom: 0;
  height: 30px;
}

//the below css are for the links, not needed for sticky nav
.nav_links {
  margin: 0;
}

.nav_links li {
  display: inline-block;
  margin-top: 4px;
}

.nav_links li a {
  padding: 0 15.5px;
  color: #3498db;
  text-decoration: none;
}

现在,只需添加JavaScript代码来根据滚动位置添加和删除固定类 fix。

$(document).ready(function() {
  //change the integers below to match the height of your upper div, which I called
  //banner.  Just add a 1 to the last number.  console.log($(window).scrollTop())
  //to figure out what the scroll position is when exactly you want to fix the nav
  //bar or div or whatever.  I stuck in the console.log for you.  Just remove when
  //you know the position.
  $(window).scroll(function () { 

    console.log($(window).scrollTop());

    if ($(window).scrollTop() > 550) {
      $('#nav_bar').addClass('navbar-fixed-top');
    }

    if ($(window).scrollTop() < 551) {
      $('#nav_bar').removeClass('navbar-fixed-top');
    }
  });
});

+1,我还创建了一个非硬编码版本,它也考虑了滚动条宽度(如果不必须为100%)和重叠的body_div。希望这可以帮到你。 - jnhghy - Alexandru Jantea
2
请注意:确保检查哪些浏览器支持 position:fixed:http://caniuse.com/#feat=css-fixed - TheCarver
2
@TheCarver 注意:它们都是(甚至在2015年也是如此)。 - TylerH

24
注意(2015年):以下问题和答案都适用于旧版已弃用的Twitter Bootstrap 2.x版本
将元素“粘性”的功能已经集成到Twitter的Bootstrap中,称为Affix。您只需要添加以下内容即可:
<div data-spy="affix" data-offset-top="121">
  ... your navbar ...
</div>

请在您的标签周围加上 class="fixed-top",并按照 手册 中所述加载Bootstrap的JS文件。数据属性offset-top指定页面滚动(从顶部)多少像素以固定菜单组件。通常它只是页面顶部的空间。
注意:当菜单被固定时,您需要处理缺失的空间。固定意味着将其从页面层中剪切并粘贴到不滚动的不同层中。我正在执行以下操作:
<div style="height: 77px;">
  <div data-spy="affix" data-offset-top="121">
    <div style="position: relative; height: 0; width: 100%;">
      <div style="position: absolute; top: 0; left: 0;">
        ... my menu ...
      </div>
    </div>
  </div>
</div>

其中77px是我固定组件的高度。


11

//在HTML中

<nav class="navbar navbar-default" id="mainnav">
<nav>

// 添加jQuery代码

$(document).ready(function() {
  var navpos = $('#mainnav').offset();
  console.log(navpos.top);
    $(window).bind('scroll', function() {
      if ($(window).scrollTop() > navpos.top) {
       $('#mainnav').addClass('navbar-fixed-top');
       }
       else {
         $('#mainnav').removeClass('navbar-fixed-top');
       }
    });
});

这里是可以玩耍的jsfiddle链接:-http://jsfiddle.net/shubhampatwa/46ovg69z/

编辑: 如果你只想在移动设备上应用此代码,那么可以使用:

   var newWindowWidth = $(window).width();
    if (newWindowWidth < 481) {
        //Place code inside it...
       }

6

Bootstrap 4 - 更新2020年

Bootstrap 4中不再使用Affix插件,但现在大多数浏览器都支持position:sticky,可用于创建滚动后固定的导航栏。Bootstrap 4包括sticky-top类用于此目的...

https://codeply.com/go/oY2CyNiA7A

Bootstrap 3 - 原始答案

以下是一个Bootstrap 3示例,不需要额外的jQuery..它使用了Bootstrap 3中包含的Affix插件,但由于BS2之后navbar标记已更改...

<!-- Content Above Nav -->
<header class="masthead">

</header>           


<!-- Begin Navbar -->
<div id="nav">
  <div class="navbar navbar-default navbar-static">
    <div class="container">
      <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
      <a class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="glyphicon glyphicon-bar"></span>
        <span class="glyphicon glyphicon-bar"></span>
        <span class="glyphicon glyphicon-bar"></span>
      </a>
      <div class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
          <li class="active"><a href="#">Home</a></li>
          <li class="divider"></li>
          <li><a href="#">Link</a></li>
          <li><a href="#">Link</a></li>
        </ul>
        <ul class="nav pull-right navbar-nav">
          <li>
            ..
          </li>
          <li>
            ..
          </li>
        </ul>
      </div>        
    </div>
  </div><!-- /.navbar -->
</div>

工作演示/模板: http://bootply.com/69848


它跳得太多了,看起来不好看。 - jemiloii

5

这对我来说非常好用。不要忘记在导航栏所在的位置放置填充器div,否则每次固定/取消固定内容时都会跳动。

function setSkrollr(){
    var objDistance = $navbar.offset().top;
    $(window).scroll(function() {
        var myDistance = $(window).scrollTop();
        if (myDistance > objDistance){
            $navbar.addClass('navbar-fixed-top');
        }
        if (objDistance > myDistance){
            $navbar.removeClass('navbar-fixed-top');
        }
    });
}

4

使用 Bootstrap Affix:

/* Note: Try to remove the following lines to see the effect of CSS positioning */
  .affix {
      top: 0;
      width: 100%;
  }

  .affix + .container-fluid {
      padding-top: 70px;
  }
<!DOCTYPE html>
<html>
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <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>
  
</head>
<body>

<div class="container-fluid" style="background-color:#F44336;color:#fff;height:200px;">
  <h1>Bootstrap Affix Example</h1>
  <h3>Fixed (sticky) navbar on scroll</h3>
  <p>Scroll this page to see how the navbar behaves with data-spy="affix".</p>
  <p>The navbar is attached to the top of the page after you have scrolled a specified amount of pixels.</p>
</div>

<nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">
  <ul class="nav navbar-nav">
    <li class="active"><a href="#">Basic Topnav</a></li>
    <li><a href="#">Page 1</a></li>
    <li><a href="#">Page 2</a></li>
    <li><a href="#">Page 3</a></li>
  </ul>
</nav>

<div class="container-fluid" style="height:1000px">
  <h1>Some text to enable scrolling</h1>
  <h1>Some text to enable scrolling</h1>
  <h1>Some text to enable scrolling</h1>
  <h1>Some text to enable scrolling</h1>
  <h1>Some text to enable scrolling</h1>
  <h1>Some text to enable scrolling</h1>
  <h1>Some text to enable scrolling</h1>
  <h1>Some text to enable scrolling</h1>
  <h1>Some text to enable scrolling</h1>
  <h1>Some text to enable scrolling</h1>
  <h1>Some text to enable scrolling</h1>
</div>

</body>
</html>


3
你可以使用 position: sticky
#navbar {
  position: sticky;
  top: 0px;
}

#navbar 应该是 body 的直接子元素。

2
这是最好的解决方案,但目前只能在FireFox上运行 :(( - John

3
对于Bootstrap 4,推出了一个新的类。根据工具文档:docs:
应用class sticky-top。
<div class="sticky-top">...</div>

如需了解更多导航栏位置选项,请访问此处。 另外,要记住的是,position: sticky;不被所有浏览器支持,所以如果您需要支持旧版本浏览器,则这可能不是最佳解决方案。


1
作为对Shubham Patwa的回应:这种方式,一旦应用了"class navbar-fixed-top"类,页面就会变得"跳跃"。这是因为#mainnav被抛入和移出文档的DOM流中。如果页面具有"关键高度",在固定和非固定#mainnav位置之间跳转可能会导致丑陋的UX。
我以这种方式改变了代码,它似乎工作得很好(不是像素完美,但很好)。
$(document).ready(function() {
  var navpos = $('#mainnav').offset();
  var navheight = $('#mainnav').outerHeight();

$(window).bind('scroll', function() {
  if ($(window).scrollTop() > navpos.top) {
   $('#mainnav').addClass('navbar-fixed-top');
   $('body').css('marginTop',navheight);
   }
   else {
     $('#mainnav').removeClass('navbar-fixed-top');
     $('body').css('marginTop','0');
   }
});

0

我发现这段简单的 JavaScript 代码非常有用。

$(document).ready(function()
{
    var navbar = $('#navbar');

    navbar.after('<div id="more-div" style="height: ' + navbar.outerHeight(true) + 'px" class="hidden"></div>');
    var afternavbar = $('#more-div');

    var abovenavbar = $('#above-navbar');

    $(window).on('scroll', function()
    {
        if ($(window).scrollTop() > abovenavbar.height())
        {
            navbar.addClass('navbar-fixed-top');
            afternavbar.removeClass('hidden');
        }
        else
        {
            navbar.removeClass('navbar-fixed-top');
            afternavbar.addClass('hidden');
        }
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接