css 滚动相关的菜单栏与CSS3和JS

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了css 滚动相关的菜单栏与CSS3和JS相关的知识,希望对你有一定的参考价值。

// https://github.com/stutrek/scrollMonitor

var menu = $('nav#menu');

var watcher = scrollMonitor.create( menu );

watcher.lock();

watcher.stateChange(function() {
  $(menu).toggleClass('scrolled', this.isAboveViewport)
});
<!--
http://creative-punch.net/2014/03/making-scroll-dependent-menu-bar-css3-javascript/
https://github.com/stutrek/scrollMonitor
-->

<h1>Scroll down</h1>
<h2>And watch the menu bar</h2>

<nav id="menu">
  <h1 id="sitename">MySite</h1>
  <ul>
    <li class="active"><a href="#">Home</a></li>
    <li><a href="#">Blog</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</nav>
@import url(http://fonts.googleapis.com/css?family=Roboto);

body {
  height: 2000px;
  font-family: Roboto, sans-serif;
  -webkit-font-smoothing: antialiased;
}

h1, h2 {
  text-align: center;
}

h1 {
  color: #222;
}

h2 {
  color: #555;
}

nav#menu {
  margin-top: 50px;
  background: #3498db;
  text-align: center;
  height: 50px;
  width: 100%;
}

nav#menu ul {
  padding: 0;
  background: white;
  margin: 0 auto;
  display: inline-block;
  height: 50px;
}

nav#menu ul li {
  float: left;
  padding: 0 20px;
  background: #3498db;
  list-style: none;
  margin-right: 5px;
  line-height: 50px;
  height: 50px;
  
  /*
   * This element will get an alternative style
   * once we apply the "scrolled" class.
   * We also want a nice animation so we can
   * simply set CSS3 transitions for this.
   */
  transition: margin 0.1s ease-in-out;
}

nav#menu ul li:nth-child(1) {
  margin-left: 5px;
}

nav#menu ul li.active {
  background: #2980b9;
}

nav#menu ul li a {
  color: white;
  text-decoration: none;
  font-size: 1.3em;
}

nav#menu h1#sitename {
  font-size: 1.2em;
  line-height: 50px;
  margin: 0;
  position: absolute;
  left: 0.5em;
  color: white;
  opacity: 0;
  
  /*
   * Same thing here as with the menu items.
   * This element will be animated into its
   * alt. state with the transition property
   */
  transition: opacity 0.1s ease-in-out;
}


/*********************************************
 * Once the 'scrolled' class is toggled 
 * we can set any alternative styling that we
 * want for the menu bar 
 *********************************************/

nav#menu.scrolled {
  margin: 0;
  position: fixed;
  top: 0;
}

nav#menu.scrolled ul li {
  margin: 0;
}

nav#menu.scrolled h1#sitename {
  opacity: 1;
}

以上是关于css 滚动相关的菜单栏与CSS3和JS的主要内容,如果未能解决你的问题,请参考以下文章

如何在HTML标签和JS中设置CSS3 var变量

css 避免管理栏与固定菜单栏重叠

案例JS+CSS3底部下划线导航菜单代码

用html5+js+css3 怎么禁止全屏手机长按弹出的功能菜单

如何在页面呈现时才开始CSS3动画

CSS3修改滚动条样式