缩小并更改滚动背景导航栏

时间:2016-05-07 03:07:00

标签: javascript html css twitter-bootstrap

我试图让我的导航栏缩小并在滚动时立即更改背景颜色。我尝试了一些类似问题中提供的一些javascript解决方案,但它似乎没有用。这是我的html的样子:

<nav id="menu" class="navbar navbar-default navbar-fixed-top">
  <div class="container"> 
    <!-- 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="index.html"><i class="fa fa-cog fa-spin fa-1x fa-fw margin-bottom" aria-hidden="true"></i> PROTOTYPE<font color="#37c6f5">MY</font>SKETCH<strong></strong></a> </div>

      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse">
        <ul class="nav navbar-nav navbar-right">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle">Contact</a>
            <ul class="dropdown-menu"> 
            </ul>
          </li>
        </ul>

        <ul class="nav navbar-nav navbar-right">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle">Services</a>
            <ul class="dropdown-menu"> 
            </ul>
          </li>
        </ul>

        <ul class="nav navbar-nav navbar-right">
          <li class="dropdown">
            <a href="about.html" class="dropdown-toggle">About</a>
          </li>
        </ul>

        <ul class="nav navbar-nav navbar-right">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle">Home</a>
            <ul class="dropdown-menu"> 
            </ul>
          </li>
        </ul>

      </div>
      <!-- /.navbar-collapse --> 
    </div>
    <!-- /.container-fluid --> 
  </nav>

真的很感激任何帮助!

1 个答案:

答案 0 :(得分:1)

Using Jquery and Css you can change the background color of navbar with scrolling:

 $(document).ready(function(){
  $(window).scroll(function() { 
    if ($(document).scrollTop() > 150) { 
      $('.navbar').addClass('shrink'); 
    } else { 
      $('.navbar').removeClass('shrink'); 
    } 
  }); 
 });

CSS for that:
.navbar{
   transition: background-color 0.5s ease;
   background-color: #f8f8f8;
}
.navbar.shrink{ 
   background: #dddddd 
}

change color as per your requirement.