How to hide/show nav bar when user scrolls up/down

后端 未结 6 1339
面向向阳花
面向向阳花 2020-12-12 18:49

Hide/show nav bar when user scrolls up/down

Here\'s the example I\'m trying to achieve: http://haraldurthorleifsson.com/ or http://www.teehanlax.com

6条回答
  •  时光说笑
    2020-12-12 18:59

    I found a similar and simpler implementation of @Dom Day written about by Saijo George.

    NOTE: I renamed Saijo's variables so it would be easier for me to read.

    CSS

    /* This class will be attached to your nav by the below */
    .scrollUp {
      transform: translateY(-100%);
    }
    

    jQuery

    const navbar = document.querySelector("nav"); //Select your nav element here
    let previousScroll = 0;
    
    $(window).scroll(function handleNav() {
      let currentScroll = $(window).scrollTop(); //Distance scrolled down the page
      let navHeight = $(navbar).height(); //Height of navbar
    
      //When scrolling down AND you've scrolled past navHeight * 2.25, add .scrollUp
      if (currentScroll > previousScroll && currentScroll > navHeight * 2.25) {
        $(navbar).addClass("scrollUp");
        //When scrolling up AND you've scrolled less than navHeight, remove .scrollUp
      } else if (previousScroll > currentScroll && !(currentScroll <= navHeight)) {
        $(navbar).removeClass("scrollUp");
      }
      previousScroll = currentScroll;
    });
    

提交回复
热议问题