繁体   English   中英

如何引导导航栏静态固定在滚动上?

[英]How to Bootstrap navbar static to fixed on scroll?

我想让静态导航栏在滚动时固定导航栏,当它到达页面顶部时。

有没有办法使用 bootstrap 3 css 或 javascript 来获取它?

如果我没记错的话,您要实现的目标称为粘性导航栏。

使用几行 jQuery 和滚动事件很容易实现:

$(document).ready(function() {

    var menu = $('.menu');
    var content = $('.content');
    var origOffsetY = menu.offset().top;

    function scroll() {
        if ($(window).scrollTop() >= origOffsetY) {
            menu.addClass('sticky');
            content.addClass('menu-padding');
        } else {
            menu.removeClass('sticky');
            content.removeClass('menu-padding');
        }
    }

    $(document).scroll();

});

我已经为您做了一个快速的工作示例,希望对您有所帮助: http : //jsfiddle.net/yeco/4EcFf/

要使其与Bootstrap 一起使用,您只需要在 jsfiddle 中添加或删除“navbar-fixed-top”而不是“sticky”类。

使用 Bootstrap 附带的affix组件。 从“navbar-static-top”开始,当达到标题(导航栏上方的内容)的高度时,这会将其更改为fixed ...

$('#nav').affix({
      offset: {
        top: $('header').height()
      }
}); 

http://bootply.com/107973

我很确定,你在期待什么。 看看这个小提琴,这可能对你有帮助。

http://jsfiddle.net/JK52L/8/

你的 HTML 应该有类navbar-fixed-topnavbar-fixed-bottom

HTML

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
  <!-- Brand and toggle get grouped for better mobile display -->
  <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 class="navbar-brand" href="#">Brand</a>
  </div>

  <!-- Collect the nav links, forms, and other content for toggling -->
  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
    </ul>
  </div><!-- /.navbar-collapse -->
</nav>

JS

$(document).scroll(function(e){
    var scrollTop = $(document).scrollTop();
    if(scrollTop > 0){
        console.log(scrollTop);
        $('.navbar').removeClass('navbar-static-top').addClass('navbar-fixed-top');
    } else {
        $('.navbar').removeClass('navbar-fixed-top').addClass('navbar-static-top');
    }
});

这是使用 Bootstrap 的词缀插件的解决方案:

HTML:

<header class="container-fluid">
    ...
</header>
<nav class="navbar navbar-default navbar-static-top" role="navigation">
    ...
</nav>

Javascript:

$('nav').affix({
      offset: {
        top: $('header').height()
      }
});

padding-top设置为您的body等于您的nav的高度,以便固定导航栏覆盖的内容可见。

$('nav').on('affix.bs.affix', function (){
     $('body').css('margin-top', $('nav').height());
});

$('nav').on('affix-top.bs.affix', function (){
     $('body').css('margin-top', 0);
});

要在滚动时使nav保持在顶部,请添加这一点 CSS。

CSS:

.affix
{
    top: 0;
}

我遇到了同样的问题,但对我有用的解决方案是:

HTML:

<header class="container-fluid">
    ...
</header>
<nav class="row">
    <div class="navbar navbar-inverse navbar-static-top">
        ...
    </div>
</nav>

JavaScript:

document.onscroll = function() {
    if( $(window).scrollTop() > $('header').height() ) {
        $('nav > div.navbar').removeClass('navbar-static-top').addClass('navbar-fixed-top');
    }
    else {
        $('nav > div.navbar').removeClass('navbar-fixed-top').addClass('navbar-static-top');
    }
};

header是导航栏上方的横幅标签

在导航上设置

style="position:fixed; width:100%;"

或者您可以使用类名更改特定div位置

$(document).scroll(function(e){
    var scrollTop = $(document).scrollTop();
    if(scrollTop > 0){
        //console.log(scrollTop);
        $('.header').css("position","fixed");
    } else {
         $('.header').css("position","relative");
    }
});

嘿,所有人都在想这件事,你需要做的就是将导航包装成如下所示:

css代码:

#navwrap {  
    height: 100px;   (change dependant on hight of nav)
    width: 100%;
    margin: 0;
    padding-top: 5px;
}

HTML:

<div id="navwrap">
    nav code inside
</div>

/** * 滚动管理 */ $(document).ready(function () {

// Define the menu we are working with
var menu = $('.navbar.navbar-default.navbar-inverse');

// Get the menus current offset
var origOffsetY = menu.offset().top;

/**
 * scroll
 * Perform our menu mod
 */
function scroll() {

    // Check the menus offset. 
    if ($(window).scrollTop() >= origOffsetY) {

        //If it is indeed beyond the offset, affix it to the top.
        $(menu).addClass('navbar-fixed-top');

    } else {

        // Otherwise, un affix it.
        $(menu).removeClass('navbar-fixed-top');

    }
}

// Anytime the document is scrolled act on it
document.onscroll = scroll;

});

 /** * Scroll management */ $(document).ready(function () { // Define the menu we are working with var menu = $('.navbar.navbar-default.navbar-inverse'); // Get the menus current offset var origOffsetY = menu.offset().top; /** * scroll * Perform our menu mod */ function scroll() { // Check the menus offset. if ($(window).scrollTop() >= origOffsetY) { //If it is indeed beyond the offset, affix it to the top. $(menu).addClass('navbar-fixed-top'); } else { // Otherwise, un affix it. $(menu).removeClass('navbar-fixed-top'); } } // Anytime the document is scrolled act on it document.onscroll = scroll; });
 .navbar-wrapper{ background:url('http://www.wallpaperup.com/uploads/wallpapers/2012/10/21/20181/cad2441dd3252cf53f12154412286ba0.jpg'); height: 100vh; padding-top: 50px; } h1{ font-size: 50px; font-weight: 700; } #login-dp{ min-width: 250px; padding: 14px 14px 0; overflow:hidden; background-color:rgba(255,255,255,.8); } #login-dp .help-block{ font-size:12px } #login-dp .bottom{ background-color:rgba(255,255,255,.8); border-top:1px solid #ddd; clear:both; padding:14px; } #login-dp .social-buttons{ margin:12px 0 } #login-dp .social-buttons a{ width: 49%; } #login-dp .form-group { margin-bottom: 10px; } .btn-fb{ color: #fff; background-color:#3b5998; } .btn-fb:hover{ color: #fff; background-color:#496ebc } .btn-tw{ color: #fff; background-color:#55acee; } .btn-tw:hover{ color: #fff; background-color:#59b5fa; } @media(max-width:768px){ #login-dp{ background-color: inherit; color: #fff; } #login-dp .bottom{ background-color: inherit; border-top:0 none; } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <body> <div class="navbar-wrapper"> <div class="container"> <nav class="navbar navbar-default navbar-inverse" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" 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 class="navbar-brand" href="#">Login dropdown</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu" role="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><a href="#">Separated link</a></li> <li class="divider"></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> </nav> </div><!-- container --> </div><!-- /.navbar-wrapper --> <section> <div class="container"> <div class="row"> <h1>Content</h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi congue luctus placerat. Sed nisl sem, pellentesque at risus eget, consequat bibendum velit. Sed interdum accumsan luctus. Duis rhoncus suscipit hendrerit. Vestibulum ut lobortis diam. Donec magna est, euismod non ligula in, congue aliquet diam. Sed pellentesque erat nibh, et blandit quam auctor eget. Integer fringilla turpis ac sagittis mattis. In in metus posuere, tincidunt orci non, lobortis ipsum. Praesent porttitor orci a ligula facilisis porta. Nullam tincidunt feugiat dignissim. </p> <p> Pellentesque cursus suscipit massa ut molestie. Duis malesuada consequat venenatis. Vestibulum accumsan lorem sit amet vehicula tristique. Donec nec mauris quis mi imperdiet vestibulum. Praesent tempor velit at posuere posuere. Mauris tellus diam, dictum sed molestie eu, lobortis nec diam. Mauris molestie nulla vulputate, lobortis urna eget, gravida erat. Phasellus in ullamcorper lacus, eget ullamcorper odio. </p> <p> Quisque gravida nulla eros. Duis sit amet rhoncus felis. Etiam in malesuada nisl. Proin sit amet elit sit amet erat dapibus pretium. Duis a dignissim lacus, vitae mollis nunc. Donec ut tempor magna. Maecenas eget felis eget ipsum porttitor dapibus vitae vitae magna. Cras et felis eros. Nam dolor odio, bibendum ut ex eu, facilisis suscipit ipsum. Aliquam sit amet nunc volutpat, aliquet nunc ut, tempor augue. Pellentesque semper vestibulum lacinia. Nam lacinia erat interdum purus consequat elementum. Phasellus volutpat sed libero id molestie. Quisque nec iaculis nisl, vitae accumsan justo. Suspendisse sollicitudin metus in libero cursus tempor in eget enim. </p> <p> Suspendisse nibh lacus, consequat et tincidunt eget, interdum mollis velit. Etiam lobortis ac tellus et pretium. Nunc a tincidunt nulla. Cras vel nulla in neque accumsan fermentum. Etiam ac erat leo. Vestibulum aliquam dignissim lectus, tincidunt consequat augue malesuada at. Pellentesque semper viverra elit quis vestibulum. Aliquam rutrum justo dignissim ligula fringilla, ac viverra metus efficitur. </p> <p> Mauris quis nisi convallis, rhoncus odio non, sodales urna. Donec ac ante at nisi pulvinar eleifend. Duis vel suscipit est. Nullam quis aliquet eros. Maecenas tincidunt augue condimentum nisi pharetra, in molestie libero condimentum. In hac habitasse platea dictumst. Morbi quis elit id nunc faucibus egestas. Sed non vehicula ligula, quis viverra urna. Nunc nec eleifend elit. Sed aliquam nibh non turpis congue, a condimentum mauris dictum. Vivamus laoreet nulla vel elit consequat, non convallis nibh dapibus. Mauris maximus nibh maximus, sollicitudin odio nec, semper nunc. Nunc consequat convallis lobortis. Aliquam pulvinar porttitor lorem. Donec luctus, libero a interdum posuere, est tellus tincidunt risus, a fermentum lacus odio at metus. Donec maximus ante massa, imperdiet consequat magna lobortis sed. </p> </div> </div> </section> </body>

根据需要设置最大高度:

.navbar-fixed-top 
.navbar-collapse, 
.navbar-fixed-bottom 
.navbar-collapse {
    max-height: 700px;
}

这是我使用 Affix Bootstrap 插件http://getbootstrap.com/javascript/#affix 的实现

它包括解决了一些额外的词缀问题(见下文)。

HTML:

<nav class="navbar navbar-inverse navbar-fixed-top" id="top_navbar">
  <div class="container-fluid">
... (typical Bootstrap top navbar)
  </div>
</div>

...
...
...

<div id="parent-navbar-main" >
  <div id="navbar-main">
... (here is your nav panel to get sticky on scroll)
  </div>
</div>

Javascript:

function set_sticky_panel()  {

  var affixElement = $('#navbar-main');

  var navbarElementHeight = $('#top_navbar').height();

// http://stackoverflow.com/questions/18683303/bootstrap-3-0-affix-with-list-changes-width
  var width = affixElement.parent().width();
  affixElement.width(width);

// http://stackoverflow.com/questions/3410765/get-full-height-of-element
  var affixElementHeight = $('#navbar-main').outerHeight(true);

// https://finiteheap.com/webdev/2014/12/26/bootstrap-affix-flickering.html  
  affixElement.parent().height(affixElementHeight);

// http://stackoverflow.com/questions/23797241/resetting-changing-the-offset-of-bootstrap-affix
  $(window).off('.affix')
  affixElement.removeData('bs.affix').removeClass('affix affix-top affix-bottom')


  affixElement.affix({
    offset: {
    // Distance of between element and top page
      top: function () {
      // how much scrolling is done until sticking the panel
        return (this.top = affixElement.offset().top - parseInt(navbarElementHeight,10))
      }
    }
  });

  // The replacement for the css-file.
  affixElement.on('affix.bs.affix', function (){
  // the absolute position where the sticked panel is to be placed when the fixing event fires (e.g. the panel reached the top of the page).
    affixElement.css('top', navbarElementHeight + 'px');
    affixElement.css('z-index', 10);
  });

}

$(document).on('ready', set_sticky_panel);

$(window).resize(set_sticky_panel);

CSS:

不需要css。

如果与标准实现进行比较,我的代码还可以解决这些问题:

  1. 粘性面板的宽度不再在固定事件中断裂。
  2. 消除了使用 CSS 文件的需要。
  3. 重新格式化窗口更改大小事件(响应性)上的粘性面板大小现在已完成。
  4. 在修复事件中不再有词缀飘动/跳跃。

如果你这样处理代码:

<div class="scroll"> 
<div class="menu">home | services | contact</div>
</div>

和CSS:

.scroll {
  margin-bottom:50px;
}
.menu {
  position:absolute;
  background:#428bca;
  color:#fff;
  line-height:30px;
  letter-spacing:1px;
  width:100%;
  height:50px;
}
.menu-padding {
  // no  style here anymore 
}

然后烦人的卷轴就消失了。

完整的代码和小提琴最初不是由我制作的,我是从本主题的早期答案中得到的。 代码中的更改是我做的

Fabian #Web-Stars

提琴手

这个问题有点老了,它是由 CSS 和最新的 bootstrap 本地解决的。

如果您将类sticky-top添加到您的导航栏中,它的行为就像当前最佳答案中的javascript/jquery 一样,但没有任何javascript。
浏览器支持相当不错,但并不完美。

如果您使用的是 Bootstrap 4(编写此答案时的最新版本),则评估会发生一些变化。 这是固定在顶部的导航栏的示例:

<nav class="navbar fixed-top navbar-light bg-light">
    <a class="navbar-brand" href="#"><h1>Navbar</h1></a>
</nav>

固定到顶部

使引导导航栏固定在滚动上

<nav class="navbar navbar-default navbar-fixed-top">
    <div class="container">
          ...
     </div> 
</nav>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM