JS 在 `display: none` 和 `display: flex` 之间切换

Mar*_*ova 0 html javascript css

我有一个 JS 函数,用于响应式导航,带有汉堡按钮,可以在屏幕太小时隐藏和显示导航。

我的问题是,即使 CSS 样式显示:none,导航的链接也会在加载时显示,之后按钮将按预期工作并让我在display: none和 之间切换display: flex。是什么导致它display: none在加载时忽略?

function myBurger() {
  var x = document.getElementById("navLinks");
  if (x.style.display === "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }
}
Run Code Online (Sandbox Code Playgroud)
.navigation1 {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 3rem 3rem;
  .logo img {
    height: 5rem;
  }
  i {
    display: none;
  }
  .navLinks {
    display: flex;
    a {
      padding-left: 2rem;
      align-self: center; //vertical align
      color: $secondaryColor;
    }
  }
}


/*responsive*/

@media (max-width: 700px) {
  #icon {
    align-self: center;
    i {
      font-size: 3rem;
      display: block;
    }
  }
  .navLinks {
    flex-direction: column;
    width: 100%;
    padding-top: 2rem;
    padding-bottom: 2rem;
    display: none;
    .nav-link {
      padding-left: 0;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)
<div class="navigation1">
  <!--nav container -->
  <div class="logo">
    <img src="logo.svg" alt="logo">
    <!--logo image -->
  </div>
  <!--burger menu -->
  <a href="javascript:void(0);" id="icon" onclick="myBurger()">
    <i class="fa fa-bars"></i>
  </a>
  <div class="navLinks" id="navLinks">
    <!--links, no need to be put in a list -->
    <a class="nav-link active" href="#">Home</a>
    <a class="nav-link" href="#">Portfolio</a>
    <a class="nav-link" href="#">Services</a>
    <a class="nav-link" href="#">About</a>
    <a class="nav-link" href="#">Contact</a>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

谢谢

Dai*_*Dai 5

x.style.display == 'none'表达式不起作用,因为HTMLElement.style属性仅返回来自内联style=""属性的属性,而不是有效或计算样式.

您想要的是getComputedStyle(),它返回应用于该元素的有效样式规则。

function myBurger() {
    const el = document.getElementById( 'navLinks' );
    if( window.getComputedStyle( el ).display === "none" ) {
        el.style.display = "flex";
    } else {
        el.style.display = ""; // unset flex, so it returns to `none` as defined in the CSS.
    }
}
Run Code Online (Sandbox Code Playgroud)

也就是说,你不需要任何 JS 来实现这一点 -只需使用-trick来<label>隐藏<input type="checkbox" />:checked ~

function myBurger() {
    const el = document.getElementById( 'navLinks' );
    if( window.getComputedStyle( el ).display === "none" ) {
        el.style.display = "flex";
    } else {
        el.style.display = ""; // unset flex, so it returns to `none` as defined in the CSS.
    }
}
Run Code Online (Sandbox Code Playgroud)
#menuTrigger { display: none; }

#menuTrigger:not(:checked) ~ #navLinks {
    display: none;
}

#menuTrigger:checked ~ #navLinks {
    display: flex;
}
Run Code Online (Sandbox Code Playgroud)