如何制作粘性菜单?

时间:2015-04-09 15:51:53

标签: jquery html css

如何在此网站上制作菜单? www.awwwards.com

使用鼠标滚动页面时,菜单将保持在顶部,其颜色也会发生变化。滚动前和滚动后的菜单有不同的颜色。

我在互联网上找到了一个教程,但在滚动页面时它只有相同的颜色。有人能告诉我如何改变颜色吗?

.menutext {
  float: left;
  border-bottom:1px solid #d2d6d5;
  width: 100%;
  background:gray; }
.menutext ul {
  margin: 0 0 0 10%; }
.menutext ul li {
  float: left;
  position: relative;
  border-left: none;
  list-style: none; 
}
.menutext li a {
  text-decoration: none;
  color: #444;
  display: inline-block;
  font-size: 14px;
  font-family: MuseoSans, serif;
  text-transform: uppercase;
  padding:10px;
  border-right: 1px solid #d2d6d5;
  text-align: center;
}
.menutext ul li :hover {
  color:#919191;
  background-color: #f4f4f4;
}

JS

$(document).ready(function() {
  // Menentukan elemen yang dijadikan normal yaitu .normal
  var normalNavTop = $('.menutext').offset().top; 
  var normalNav = function(){
    var scrollTop = $(window).scrollTop();  
    // Kondisi jika discroll maka .nav ditambahkan class normal dan sebaliknya      
    if (scrollTop > normalNavTop) { 
        $('.menutext').css({ 'position': 'fixed', 'top':0, 'left':0, 'z-index':9999 });
    } else {
      $('.menutext').css({ 'position': 'relative' });
    }
  };

  // Jalankan fungsi
  normalNav();
  $(window).scroll(function() {
    normalNav();
  });
});

HTML

<div id="menu">
<div class="menutext">
    <ul>
        <li><a href="#">home</a>
        </li>
        <li><a href="#">about</a>
        </li>
        <li><a href="#">product</a>
        </li>
    </ul>
</div>

Full code here

1 个答案:

答案 0 :(得分:4)

&#13;
&#13;
$(window).scroll(function () {
  if($(window).scrollTop() > 20) {
    $("#head").addClass('sticky');
  } else {
    $("#head").removeClass('sticky');
  }
});
&#13;
html,body {
  margin: 0;padding: 0;
  height: 300%;
}
  
#top {
  height: 20px;
  width: 100%;
}

#head {
  width: 100%;
  height: 50px;
  background-color:gray;
}

.sticky {
  position: fixed;
  top: 0;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="top">Blah blah</div>
<div id="head">Sticky Header</div>
&#13;
&#13;
&#13;