为什么我的Javascript不能正常工作?

Emm*_*ies 1 html javascript css if-statement

我一直在搞乱这个移动友好的导航菜单,由于某种原因,我的菜单将打开(JS IF语句),但不关闭(JS ELSE声明.所以我坚持为什么它打开但不关闭?

PS我是JavaScript的新手,所以我看起来可能很简单,谢谢!

这是我正在使用的代码:

function myFunction(x) {
    x.classList.toggle("change");
}


function navChange() {
    var x = document.getElementById("myNav").style.height
    if (x = "0%"){
     document.getElementById("myNav").style.height = "100%";
    } else {
     document.getElementById("myNav").style.height = "0%";
    }
}
Run Code Online (Sandbox Code Playgroud)
.overlay {
    height: 0%;
    width: 100%;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: rgb(0,0,0);
    background-color: rgba(0,0,0, 0.9);
    overflow-y: hidden;
    transition: 0.5s;
}

.overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 30px;
}

.overlay a {
    padding: 8px;
    text-decoration: none;
    font-size: 36px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

@media screen and (max-height: 450px) {
  .overlay {overflow-y: auto;}
  .overlay a {font-size: 20px}
  .closebtn {
    font-size: 40px !important;
    top: 15px;
    right: 35px;
  }
}

.container {
    position: absolute;
    top: 25px;
    left: 25px;
    display: inline-block;
    cursor: pointer;
    margin: 20px;
    z-index: 12;
}

.bar1, .bar2 {
    width: 35px;
    height: 4px;
    background-color: #333;
    margin: 6px 0;
    transition: 0.4s;
}

.change .bar1 {
    transform: rotate(-45deg) translate(0px, 0px) ;
    background-color: gray;
}

.change .bar2 {
    transform: translate(1px, -10px) rotate(45deg);
    background-color: gray;
}
Run Code Online (Sandbox Code Playgroud)
<div id="myNav" class="overlay">
  <div class="overlay-content">
    <a href="#">About</a>
    <a href="#">Services</a>
    <a href="#">Clients</a>
    <a href="#">Contact</a>
  </div>
</div>

<div class="container" onclick="myFunction(this), navChange()">
  <div class="bar1"></div>
  <div class="bar2"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

感谢您的时间和精力!

Eas*_*yBB 5

我看到的错误的原因是你在条件下做的任务.

a = 15;
b = 10;
if(a = b) alert("hello world");
Run Code Online (Sandbox Code Playgroud)

现在是现在10,因为我们使用赋值而不是测试看起来像的相等性.

if( a == b)
Run Code Online (Sandbox Code Playgroud)

此外,您正在测试样式属性,看起来您正在通过CSS进行设置,并且style.height不会返回您要查找的内容.你需要测试PX或你有什么.

var height =  window.getComputedStyle(document.getElementById("element")).height;
var height = parseInt(height,10);
if( height > 1510 ) {
    //do whatever
}
Run Code Online (Sandbox Code Playgroud)