问题是构建固定的粘性侧边栏

时间:2016-03-27 17:00:23

标签: javascript jquery html css twitter-bootstrap

我正在学习bootstrap,我希望我的自定义水平导航栏一旦到达它就会粘在页面顶部(如this)。 我试图在我的CSS和一段JS代码中添加一个词缀类,但这不起作用。有什么问题? 见https://jsfiddle.net/bs7bdpmh/

HTML

<div id="nav" class="container-fluid">
  <nav class="navbar-classic">
    <li><a href="index.html" class="active">Who are we? </a>
      <ul class="dropdown">
        <li><a href="#">Sub 1</a></li>
        <li><a href="#">Sub 2</a></li>
      </ul>
    </li>
    <li><a href="#">Services Services Services</a>
    </li>
    <li><a href="#">Products Products Products</a>
    </li>
  </nav>

CSS

#nav.affix {
    position: fixed;
    top: 0;
    width: 100%;
    height: 70px;
    background: #fff;
    z-index:10;
}

JS

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

2 个答案:

答案 0 :(得分:0)

你的意思是这样的吗?

See this fiddle

JS:

$(window).scroll(function(){
    scrollTop = $(window).scrollTop();
  if(scrollTop > 50){
    $('#nav').addClass('affix');
  }else{
    $('#nav').removeClass('affix');
  }
});

当然,它并不完美,我让你适应CSS代码和HTML结构;)

答案 1 :(得分:0)

如果您使用的是正常的引导程序,则解决方案很简单

 <style>
  /* Note: Try to remove the following lines to see the effect of CSS positioning */
  .affix {
      top: 0;
      width: 100%;
  }

  .affix + .container-fluid {
      padding-top: 70px;
  }
  </style>
</head>
<body>

<div class="container-fluid" style="background-color:#F44336;color:#fff;height:200px;">
  <h1>Bootstrap Affix Example</h1>
  <h3>Fixed (sticky) navbar on scroll</h3>
  <p>Scroll this page to see how the navbar behaves with data-spy="affix".</p>
  <p>The navbar is attached to the top of the page after you have scrolled a specified amount of pixels.</p>
</div>

<nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">
  <ul class="nav navbar-nav">
    <li class="active"><a href="#">Basic Topnav</a></li>
    <li><a href="#">Page 1</a></li>
    <li><a href="#">Page 2</a></li>
    <li><a href="#">Page 3</a></li>
  </ul>
</nav>

如果您想在滚动到底部时更改导航栏,请使用以下内容:

$(window).scroll(function(){
      if($(window).scrollTop() + $(window).height() == $(document).height())
      {
        $('#nav').addClass('affix');
      }

});