Подтвердить что ты не робот

Как загрузочный navbar статический для фиксированного прокрутки?

Я бы хотел, чтобы статический navbar фиксировал navbar при прокрутке, когда он достигает верхней части страницы.

Есть ли способ получить его, используя bootstrap 3 css или javascript?

4b9b3361

Ответ 1

Если я не ошибаюсь, то, что вы пытаетесь достичь, называется Sticky Navbar.

С помощью нескольких строк 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, вам нужно только добавить или удалить "navbar-fixed-top" вместо "sticky" класса в jsfiddle.

Ответ 2

Используйте компонент affix, включенный в Bootstrap. Начните с "navbar-static-top", и это изменит его на fixed, когда будет достигнута высота вашего заголовка (содержимое над навигационной панелью)...

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

http://bootply.com/107973

Ответ 3

Я уверен, что вы ожидаете. Посмотрите на эту скрипку, это может вам помочь.

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

У вас должен быть класс HTML navbar-fixed-top или navbar-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');
    }
});

Ответ 4

Здесь решение, использующее плагин Bootstrap affix:

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;
}

Ответ 5

У меня была та же проблема, но решение, которое сработало для меня, было:

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 был тегом баннера над моей навигационной панелью

Ответ 6

Установить на nav

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

Ответ 7

Или вы можете изменить положение конкретного div, используя имя класса

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

Ответ 8

Привет всем, все думают, что все, что вам нужно сделать, - это обернуть навигатор следующим образом:

csscode:

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

HTML:

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

Ответ 9

/** * Управление прокруткой */$ (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;

});

Ответ 10

установите максимальную высоту по мере необходимости:

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

Ответ 11

Вот моя реализация с использованием плагина 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.

Если сравнивать с стандартной реализацией, мой код дополнительно решает эти проблемы:

  • Ширина липкой панели больше не прерывается при фиксации.
  • Необходимость использования CSS файла устранена.
  • Выполняется преобразование размера липкой панели в событие изменения размера окна (отзывчивость).
  • Больше не будет аффикса flittering/прыгать на событие фиксации.

Ответ 12

Если вы обрабатываете код следующим образом:

<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 
}

Тогда раздражающий свиток исчез.

Код дополнения и скрипка изначально не сделаны мной, я получил его из более раннего ответа в этом разделе. Изменение кода производится мной

Фабиан # Веб-звезды

jsfiddle

Ответ 13

/**
 * 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>

Ответ 14

Вопрос немного старше, он решен с помощью CSS и последней загрузки.

Если вы добавите класс sticky-top на панель навигации, он будет вести себя так же, как javascript/jquery в лучшем текущем ответе, но без какого-либо javascript.
Поддержка браузера вполне приличная, но не идеальная.