twitter-bootstrap 如何使用 Twitter Bootstrap 将导航栏置于顶部?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15317499/
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-10-21 16:36:15  来源:igfitidea点击:

How do I affix top my navbar with Twitter Bootstrap?

twitter-bootstrap

提问by Lloyd Banks

I have a nav-bar that starts off at about 50px from the top of the page on load. As I scroll down, I would like the nav-bar to "affix" itself to the very top of the page and be visible as I scroll through the rest of the content. This is similar to what the nav-bar does on the official bootstrap tutorial Github site.
I am able to get the nav-bar to stay in place (albeit always 50px from the top as I scroll down the page) by using

我有一个导航栏,它在加载时距页面顶部约 50 像素处开始。当我向下滚动时,我希望导航栏将自身“附加”到页面的最顶部,并在我滚动浏览其余内容时可见。这与官方引导教程 Github 站点上的导航栏所做的类似。
我可以使用

<ul class = "nav nav-list bs-docs-sidenav affix">

but once I add "-top" to the above so that it looks like

但是一旦我在上面添加“-top”,它看起来像

<ul class = "nav nav-list bs-docs-sidenav affix-top">

the nav-bar no longer stays in place and disappears from view as I scroll down the page.

当我向下滚动页面时,导航栏不再保持原位并从视图中消失。

jsfiddle without "-top"

没有“-top”的jsfiddle

jsfiddle with "-top"

jsfiddle 与“-top”

How do I get the nav-bar to affix to the top of the page as I scroll down?

当我向下滚动时,如何让导航栏贴在页面顶部?

回答by Marcin Skórzewski

There are few things to correct. See fixed jsfiddle.

有几件事要纠正。请参阅固定的jsfiddle

  1. Affix is implemented in the Bootstrap as JavaScript code using jQuery and you did not include neither BS's JS nor jQuery
  2. To turn on affix for the element, according to official documentation, use data-spy="affix", not the class="affix". Why did you do that? Classes affixand affix-topserve a different purpose - they tell you the state of the affix at the time. If at the moment your element is fixed the class is affix, if it is scrollable BS changes the class to affix-top.
  3. You have to tell BS when you want the element to be fixed. The distance in pixels (how much you have to scroll) is set with the attribute data-offset-top. Also specify in CSS how the nav should look like when fixed. If it is binded to the top (with no space between the window border and the element) then .affix { top:0; }will do it.
  1. 词缀在 Bootstrap 中作为 JavaScript 代码使用 jQuery 实现,并且您既没有包含 BS 的 JS 也没有包含 jQuery
  2. 要打开元素的词缀,根据官方文档,使用data-spy="affix",而不是class="affix". 你为什么这么做?类affixaffix-top服务于不同的目的 - 它们会告诉您当时词缀的状态。如果此时您的元素是固定的affix,则类是,如果它是可滚动的 BS 将类更改为affix-top.
  3. 当您想要修复元素时,您必须告诉 BS。以像素为单位的距离(您必须滚动多少)由属性设置data-offset-top。还要在 CSS 中指定固定后导航的外观。如果它绑定到顶部(窗口边框和元素之间没有空间),那么.affix { top:0; }就会这样做。