首页 > 解决方案 > How to stick a static header when scrolling

问题描述

I am trying to make my header/navbar fixed when you scroll down to the content. My header is static, I tried to change its value to fixed at the beginning, but if I do that, it disappears immediately.

I wanted to implement the example of W3School, but it didnt work and I dont know why. I also kept reading all the tutorials and Questions, but mostly they could solve it but changing the position to fixed.

window.onscroll = function() {
  myFunction()
};

var header = document.getElementById("myHeader");
var sticky = header.offsetTop;

function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}
.navbar {
  background-color: #AA0000;
  width: 100vw;
  position: static;
}

.logo a {
  font-family: 'Lobster';
  font-size: 40px;
  float: left;
  text-decoration: none;
  color: white;
  padding: 20px 35px;
}

.navcontent {
  margin-left: 30%;
  display: flex;
}

.navcontent a {}

.navcontent a::after {}

.navcontent a:hover::after {}

.dropdown-content {}

.dropdown:hover .dropdown-content {}

label {
  margin: 0 auto;
  font-size: 26px;
  line-height: 70px;
  display: none;
  position: static;
}

#toggle {
  display: none;
}

.sticky {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}
HTML FIlE

<body>
  <section class="navbar" id="myHeader">
    <div class="logo">
      <a href="index.html">Test</a>
    </div>

    <label for="toggle" style="color: white;">&#9776;</label>
    <input type="checkbox" id="toggle" />

    <div class="navcontent">
      <p><a href="index.html">Start</a></p>
      <p><a href="puravida.html">Pura Vida</a></p>

      <div class="dropdown">
        <p><a href="reisen.html">Reisen</a></p>
        <div class="dropdown-content">
          <p><a href="blog/reiseinfos.html">Frag mich</a></p>
          <p><a href="reiseberichte.html">Reiseblog</a></p>
        </div>
      </div>

      <p><a href="aboutme.html">Über mich</a></p>
      <p><a href="contact.html">Kontakt</a></p>
    </div>
  </section>
  <p>...</p>
  <p>...</p>
  <p>...</p>
  <p>...</p>
  <p>...</p>
  <p>...</p>
  <p>...</p>
  <p>...</p>
  <p>...</p>
  <p>...</p>
  <p>...</p>
  <p>...</p>
  <p>...</p>

</body>

I hoped that the the W3School example could work because to my mind I just needed to implement the JS File and the .sticky class, but at the end I dont see any reaction/change

标签: javascripthtmlcss

解决方案


You can use the z-index property to show it above.

.navbar{
 position: fixed;
 top: 0;
 left: 0;
 background-color: #AA0000;
 width: 100vw;
 z-index: 99;
}

推荐阅读