为什么我必须单击2次才能运行此功能?

问题描述

这是我正在处理的代码,我不知道为什么每次刷新页面时都需要单击2次以打开菜单。一旦我第二次单击全部正常。 这是按钮的html:

var x = document.getElementById("overlay-menu");
x.style.height = "0%";

function showMenu() {
  var x = document.getElementById("overlay-menu");
  if (x.style.height === "0%") {
    x.style.height = "100%";
  } else {
    x.style.height = "0%";
  }
}
.overlay-menu {
  width: 100%;
  height: 0%;
  padding: 0;
  margin: 0;
  background-color: #ffffff;
  z-index: 10000;
  position: fixed;
  color: #0A0A0A;
  overflow: hidden;
  display: block;
  transition: .5s cubic-bezier(.55,.03,.26,1.01);
}

.nav-menu-text {
  width: fit-content;
  height: fit-content;
  margin: 0;
  padding: 0;
  color: #EB761D;
  font-size: 15px;
  position: relative;
  top: 2.8em;
  cursor: pointer;
}
<p class="nav-menu-text" onclick="showMenu()">MENU</p>

<div class="overlay-menu" id="overlay-menu">
  <!-- code of the menu -->
</div>

解决方法

x.style.height在代码运行时可能不是“ 0%”,请尝试从以下条件更改条件:

if (x.style.height === "0%") {

if (x.style.height !== "100%") {

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...