! Сегодня

Главная » Web и Технологии » Адаптивная навигационная панель со скрытием при прокрутке вниз

Адаптивная навигационная панель со скрытием при прокрутке вниз

Не всегда просит прощения тот, кто виноват. Просит прощения тот, кто дорожит отношениями.

27-сентября-2023, 22:34   6   0

Адаптивная навигационная панель со скрытием при прокрутке вниз

Адаптивная навигационная панель со скрытием при прокрутке вниз и отображением при прокрутке вверх. Простой пример скрытия navbar при прокрутке вниз.

В этом примере мы сначала определяем постоянную переменную navbar и переменную let LastScrollPosition , чтобы отслеживать позицию прокрутки пользователя. Затем мы добавляем прослушиватель событий для события прокрутки объекта окна.

Внутри прослушивателя событий мы получаем текущую позицию прокрутки, используя свойство window.pageYOffset . Затем мы проверяем, прокрутил ли пользователь вниз или вверх (что определяется путем сравнения текущей позиции прокрутки с предыдущей позицией, хранящейся в переменной LastScrollPosition ). Если пользователь прокрутил страницу вниз, мы добавляем класс .hide к элементу навигационной панели, чтобы скрыть его. В противном случае мы удаляем класс .hide, чтобы показать его. Затем мы обновляем переменную LastScrollPosition для следующего события.

HTML

 <header>
        <div class="logo">LOLearn</div>
        <input type="checkbox" id="nav_check" hidden>
        <nav>
            <ul>
                <li>
                    <a href="" class="active">Home</a>
                </li>
                <li>
                    <a href="">Portfolio</a>
                </li>
                <li>
                    <a href="">Blog</a>
                </li>
                <li>
                    <a href="">Services</a>
                </li>
                <li>
                    <a href="">About</a>
                </li>
            </ul>
        </nav>
        <label for="nav_check" class="hamburger">
            <div></div>
            <div></div>
            <div></div>
        </label>
    </header>

    <section class="section1">Hello
    </section>
    <section class="section2">Hi
    </section>
  </main>


CSS

* {
    margin: 0;
    padding: 0;
    font-family: "futura md bt";
    text-decoration: none;
    list-style: none;
    box-sizing: border-box;
}
body {
    background: dodgerblue;
}
section{
    display: flex;
  align-items: center;
  justify-content: center;

}
.section1{
  min-height:100vh;
  background:#ffddff;
}

.section2{
  min-height:100vh;
  background:#fddddf;
}
header {
    background: #fff;
    width: 100%;
    height: 70px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 50px;
     position: fixed;
  top: 0;
  left: 0;
  right: 0;
  transition: transform 0.3s ease-in-out;
  z-index: 9999;
}
header.hide {
  transform: translateY(-100%);
}
header .logo {
    font-size: 30px;
    text-transform: uppercase;
}
header nav ul {
    display: flex;
}
header nav ul li a {
    display: inline-block;
    color: #000;
    padding: 5px 0;
    margin: 0 10px;
    border: 3px solid transparent;
    text-transform: uppercase;
    transition: 0.2s;
}
header nav ul li a:hover,
header nav ul li a.active {
    border-bottom-color: dodgerblue;
}
.hamburger {
    cursor: pointer;
    display: none;
}
.hamburger div {
    width: 30px;
    height: 3px;
    margin: 5px 0;
    background: #000;
}
@media only screen and (max-width: 900px) {
    header {
        padding: 0 30px;
    }
}
@media only screen and (max-width: 700px) {
    .hamburger {
        display: block;
    }
    header nav {
        position: absolute;
        width: 100%;
        left: -100%;
        top: 70px;
        width: 100%;
        background: #fff;
        padding: 30px;
        transition: 0.3s;
    }
    header #nav_check:checked ~ nav {
        left: 0;
    }
    header nav ul {
        display: block;
    }
    header nav ul li a {
        margin: 5px 0;
    }
}


JS

// const navbar = document.querySelector('header');


// let lastScrollPosition = 0;
// window.addEventListener('scroll', () => {
//   const currentScrollPosition = window.pageYOffset || document.documentElement.scrollTop;

//   // Determine the scroll direction
//   const scrollDirection = currentScrollPosition > lastScrollPosition ? 'down' : 'up';

//   if (scrollDirection === 'down' && currentScrollPosition > navbar.offsetHeight) {
//     navbar.classList.add('hide');
//   }
//   if (scrollDirection === 'up' || currentScrollPosition <= navbar.offsetHeight) {
//     navbar.classList.remove('hide');
//   }
//   lastScrollPosition = currentScrollPosition;
// });


const header = document.querySelector("header");
// Set the initial scroll position
let lastScrollPosition = 0;
// // Add an event listener for the scroll event
window.addEventListener("scroll", () => {
  // Get the current scroll position
  let currentScrollPosition = window.pageYOffset;
  
  if (currentScrollPosition - lastScrollPosition > 0) {
    // If the scroll direction is down and the user has scrolled past the navbar, hide the navbar
    header.classList.add("hide");
  } else {
     // If the scroll direction is up or the user is at the top of the page, show the navbar
    header.classList.remove("hide");
  }
  // Set the last scroll position to the current scroll position
  lastScrollPosition = currentScrollPosition;
})


Поделиться

Tags

  • bowtiesmilelaughingblushsmileyrelaxedsmirk
    heart_eyeskissing_heartkissing_closed_eyesflushedrelievedsatisfiedgrin
    winkstuck_out_tongue_winking_eyestuck_out_tongue_closed_eyesgrinningkissingstuck_out_tonguesleeping
    worriedfrowninganguishedopen_mouthgrimacingconfusedhushed
    expressionlessunamusedsweat_smilesweatdisappointed_relievedwearypensive
    disappointedconfoundedfearfulcold_sweatperseverecrysob
    joyastonishedscreamtired_faceangryragetriumph
    sleepyyummasksunglassesdizzy_faceimpsmiling_imp
    neutral_faceno_mouthinnocent
Что приходит после зимы ?

Редакторы выбирают

Web и Технологии