如何将导航栏静态引导到固定滚动?

时间:2014-01-23 06:52:09

标签: javascript jquery html5 css3 twitter-bootstrap-3

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

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

15 个答案:

答案 0 :(得分:69)

如果我没错,那么你想要实现的就是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 一起使用,您只需在jsfiddle中添加或删除“navbar-fixed-top”而不是“sticky”类。

答案 1 :(得分:22)

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

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

http://bootply.com/107973

答案 2 :(得分:10)

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

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

答案 3 :(得分:7)

这是使用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

要让.affix { top: 0; } 在滚动时保持最佳状态,请添加此CSS。

<强> CSS:

{{1}}

答案 4 :(得分:4)

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

<强> 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是导航栏上方的横幅广告

答案 5 :(得分:3)

设置导航

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

答案 6 :(得分:2)

  

或者您可以使用班级名称

更改特定div的排名
$(document).scroll(function(e){
    var scrollTop = $(document).scrollTop();
    if(scrollTop > 0){
        //console.log(scrollTop);
        $('.header').css("position","fixed");
    } else {
         $('.header').css("position","relative");
    }
});

答案 7 :(得分:1)

嘿,所有人都在思考这一切你需要做的就是将导航包裹在下面:

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>

答案 8 :(得分:1)

/ **  *滚动管理  * / $(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;

});

答案 9 :(得分:0)

根据需要设置max-height:

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

答案 10 :(得分:0)

以下是使用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. 在定期活动中不再有人在乱窜/跳跃。

答案 11 :(得分:0)

如果你处理这样的代码:

<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

jsfiddle

答案 12 :(得分:0)

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

答案 13 :(得分:0)

如果您正在使用Bootstrap 4(即撰写此答案的最新版本),则说明情况有所变化。这是固定在顶部的导航栏的示例:

public class MainActivity extends AppCompatActivity  implements DatePickerDialog.OnDateSetListener {
TextView mChangeDateField;
@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mChangeDateField = findViewById(R.id.changeDateField);

}

public void setDateText(View view){
    ClientChooseDateFragment newFragment =
            new ClientChooseDateFragment();
    newFragment.show(getSupportFragmentManager(),
            "datePicker");

}

@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    mChangeDateField.setText("-- " + year + "--- Month" +month);
}


public static class  ClientChooseDateFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();

        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Activity needs to implement this interface
        DatePickerDialog.OnDateSetListener listener = (DatePickerDialog.OnDateSetListener) getActivity();
        DatePickerDialog q = new DatePickerDialog(getActivity(), listener, year, month, day);

        return q;
    }
}}

答案 14 :(得分:-1)

这个问题有点老了,它由CSS和最新的引导程序本机解决。

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