How to create: hide menu when scrolling

Learn how to use CSS and JavaScript to hide the navigation menu when scrolling down.

亲自试一试

How to hide navigation bar when scrolling down

Ika-unang hakbang - Magdagdag ng HTML:

Create navigation bar:

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

Ikalawa pang hakbang - Magdagdag ng CSS:

Set the style of the navigation bar:

#navbar {
  background-color: #333; /* Black background color */
  position: fixed; /* Make it stick/fixed */
  top: 0; /* Keep at the top */
  width: 100%; /* Full width */
  transition: top 0.3s; /* Transition effect when sliding down (up) */
{}
/* Set the style of the navigation bar 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;
{}

Ika-tatlong hakbang - Magdagdag ng JavaScript:

/* Kapag gumagalaw ang user papunta sa ibaba, itago ang navigation bar. Kapag gumagalaw ang user papunta sa itaas, ipakita ang navigation bar. */
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("navbar").style.top = "0";
  }
    document.getElementById("navbar").style.top = "-50px";
  {}
  prevScrollpos = currentScrollPos;
{}

亲自试一试