简体   繁体   English

移动菜单切换按钮不关闭

[英]mobile menu toggle button doesnt close

Having a few issues with my javascript code to toggle the opening and closing of a mobile menu.我的 javascript 代码在切换移动菜单的打开和关闭时遇到了一些问题。 The below code works for opening the menu = style.height: 200px, but once the menu is open, clicking on the button doesn't close the menu bar (style.height: 0) as expected.以下代码适用于打开菜单 = style.height: 200px,但是一旦打开菜单,单击按钮不会按预期关闭菜单栏 (style.height: 0)。

Anyone have some pointers as too where i'm going wrong with my code?任何人也有一些指示,我的代码哪里出错了?

 document.getElementById("hamburger").addEventListener("click", toggleNav); function toggleNav(){ navSize = document.getElementById("mobilemenu").style.height; if (navSize == 200) { return close(); } return open(); } function open() { document.getElementById("mobilemenu").style.height = "200px"; } function close() { document.getElementById("mobilemenu").style.height = "0"; }
 <div class="menubutton"> <button id="hamburger" class="hamburger hamburger--collapse" type="button" onclick="toggleNav()"> <span class="hamburger-box"> <span class="hamburger-inner"></span> </span> </button> </div>

You're testing for the wrong value in toggleNav()您正在测试toggleNav()中的错误值

Use if (navSize == "200px")使用if (navSize == "200px")

this is the faulty code:这是错误的代码:

    if (navSize == 200) {
      return close();
    }
    return open();

navSize will be something like "200px" , not 200 navSize 将类似于"200px" ,而不是200
Since the if statement is always false, it only runs open()由于 if 语句总是假的,它只运行open()

you can simply do that using classList.toggle您可以使用classList.toggle简单地做到这一点

 document.getElementById("hamburger").addEventListener("click", function (e) { e.preventDefault(); document.getElementById("mobilemenu").classList.toggle('show'); });
 .menubutton { position: fixed; top:10px; left:10px; z-index: 999; } #mobilemenu { position: fixed; top: 0; left: 0; bottom: 0; width: 200px; transform: translateX(-100%); border-right: 1px solid #ccc; background-color: #eee; transition: transform.3s ease; } #mobilemenu.show { transform: translateX(0); }
 <div class="menubutton"> <button id="hamburger" class="hamburger hamburger--collapse" type="button"> <span class="hamburger-box"> <span class="hamburger-inner">Click</span> </span> </button> </div> <div id="mobilemenu"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM