目录

如何 - 隐藏滚动菜单


了解如何使用 CSS 和 JavaScript 隐藏向下滚动的导航菜单。


亲自试一试 »


如何在向下滚动时隐藏导航栏

步骤1)添加HTML:

创建导航栏:

示例

<div id="navbar">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
</div>

步骤2)添加CSS:

导航栏样式:

示例

#navbar {
  background-color: #333; /* Black background color */
  position: fixed; /* Make it stick/fixed */
  top: 0; /* Stay on top */
  width: 100%; /* Full width */
  transition: top 0.3s; /* Transition effect when sliding down (and up) */
}

/* Style the navbar links */
#navbar a {
  float: left;
  display: block;
  color: white;
  text-align: center;
  padding: 15px;
  text-decoration: none;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}


步骤 3) 添加 JavaScript:

示例

/* When the user scrolls down, hide the navbar. When the user scrolls up, show the navbar */
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("navbar").style.top = "0";
  } else {
    document.getElementById("navbar").style.top = "-50px";
  }
  prevScrollpos = currentScrollPos;
}
亲自试一试 »