【问题标题】:How to back to className when menu is hide隐藏菜单时如何返回className
【发布时间】:2018-12-20 18:29:21
【问题描述】:

我想让移动菜单女巫改变背景颜色和高度从(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”。好的,我这样做了,但是如何在隐藏菜单后返回“导航-滚动”。当然只有当它有这个类?

【问题讨论】:

    标签: javascript html css dom


    【解决方案1】:

    我为您试了一下,但 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"); 
      }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-17
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多