简体   繁体   中英

How to stick a div/navigation bar to the top of the window when scrolled past it

I have a menu navbar that is right after a header

<header>
<center>
<img src=""> Some other stuff
</center>
</header>

<div class="navbar">
<div class="nav">
<ul class="meniunav">
<li><a href=""><img src="home.svg" class="navicon"> Home</a></li>
<li><a href=""><img src="info.svg" class="navicon"> Info</a></li>
<li><a href=""><img src="contact.svg" class="navicon"> Contact</a></li>
</ul>
</div>
</div>

The header has 150px height and I want to make the navbar element stick to the top of the page if it gets there. To be more clear: when I scroll down I want that element to get fixed at the top when it reaches it and if I scroll back up and it reaches the initial position to remove the fixed position. How can I do this?

you have two ways to do it:

First: use position: sticky; which works only on firefox (we will have to wait lot of time for this to come in standard)

Second (working on every browser): javascript. There are many scripts on the internet, and you can easily find them. just type "Sticky Navigation" in Google. Here is example of it: https://codepen.io/Guilh/pen/JLKbn

Ok so apparently the simplest method is:

$(window).scroll(function() {
  if($(this).scrollTop() >= 150) {
    $(".navbar").addClass("sticky");
  }
  else {
    $(".navbar").removeClass("sticky");
  }
});

With the sticky class containing:

.sticky {
position: fixed;
top: 0;
}

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