簡體   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