简体   繁体   中英

On Scroll Header with fixed SIdebar

I am trying to have a on scroll header with a div that stays fixed underneath the navbar as it scrolls down. I am using the code from w3schools for the header part, but i am having trouble to add the fixed div.

在此处输入图片说明 My code so far:

HTML

<div class="header">
  <h2>Scroll Down</h2>
  <p>Scroll down to see the sticky effect.</p>
</div>

<div id="navbar">
  <a class="active" href="javascript:void(0)">Home</a>
  <a href="javascript:void(0)">News</a>
  <a href="javascript:void(0)">Contact</a>
</div>

<div class="content">
  <div style="width: 100vw;padding-left: 10%;padding-right: 10%">
     <div style="min-width: 300px;width: 300px;float: left"></div>
     <div style="min-width: 600px;width: 600px;float: left"></div>
  </div>
</div>

JS

var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}

CSS

    .header {
      background-color: #f1f1f1;
      padding: 30px;
      text-align: center;
    }

    #navbar {
      overflow: hidden;
      background-color: #333;
    }

    #navbar a {
      float: left;
      display: block;
      color: #f2f2f2;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
      font-size: 17px;
    }
    .sticky {
      position: fixed;
      top: 0;
      width: 100%;
    }

    .sticky + .content {
      padding-top: 60px;
    }

You need to detect window scroll. You can do it with:

window.onscroll = function() {
    //  Do something on scroll
};

Now just do that comparison inside it, or call your function inside it:

window.onscroll = function() {
    if (window.pageYOffset >= sticky) {
        navbar.classList.add("sticky");
    } else {
        navbar.classList.remove("sticky");
    }
};

Working fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM