菜单隐藏时如何返回到className

时间:2018-12-20 18:29:22

标签: javascript html css dom

我想让移动菜单将背景颜色和高度从(10%更改为100%。当菜单处于活动导航状态时-悬停所有页面以变暗)

const nav = document.getElementById("navigation");
const burger = document.getElementById("mobileBurger");
const menu = document.getElementById("mobileMenu");

burger.addEventListener("click", function() {
  nav.classList.toggle("nav--active");

  if (nav.classList.contains("nav--scroll")) {
    nav.classList.remove("nav--scroll");
  }

  console.log(nav.classList.contains("nav"));
});

window.addEventListener("scroll", function() {
  let scrolled = window.pageYOffset;

  if (scrolled >= 40) {
    nav.classList.add("nav--scroll");
  } else nav.classList.remove("nav--scroll");
});

当nav是“ nav-scrolled”,并且我单击按钮时,我只想保留class =„ nav nav-active”。好的,我这样做了,但是如何在隐藏菜单后返回“导航—滚动”。当然只有当这堂课的时候?

1 个答案:

答案 0 :(得分:0)

我为您刺中了它,但是html将有助于测试它。 注意,将滚动检查移到了一个单独的函数以在需要时调用。

const nav = document.getElementById("navigation");
const burger = document.getElementById("mobileBurger");
const menu = document.getElementById("mobileMenu");

burger.addEventListener("click", function() {
  // toggle returns a true or false based on if it adds/removes
  if( nav.classList.toggle("nav--active") == false) {
    // if it added (made inactive), lets check and see if scroll also applies.
    checkScrolled();
  } else {
    if (nav.classList.contains("nav--scroll")) {
      nav.classList.remove("nav--scroll");
    }
  }

  console.log(nav.classList.contains("nav"));
});

window.addEventListener("scroll", function() {
  checkScrolled();
});

function checkScrolled() {
    let scrolled = window.pageYOffset;

  if (scrolled >= 40 && nav.classList.contains("nav--scroll") == false) {
    nav.classList.add("nav--scroll");
  } else { 
    nav.classList.remove("nav--scroll"); 
  }
}