简体   繁体   中英

When I click on the menu button It is not opening the menu

 const menuBtn = document.querySelector('#menuBtn') const exitBtn = document.querySelector('#exitBtn'); const menu = document.getElementsByClassName('menu'); menuBtn.addEventListener('click' , () => { menu.style.display = 'block' })
 .fa.fa-bars.menuBtn { color: #fff; font-size: 35px; cursor: pointer; display: none; } .fa.fa-times-circle.exit { color: white; font-size: 35px; cursor: pointer; } @media (max-width: 934px) { .max-width { padding: 0 50px; } .fa.fa-bars.menuBtn { display: block; } .navbar .menu { position: fixed; height: 100vh; width: 100%; left: 0; top: 0; background-color: #111; text-align: center; padding-top: 110px; display: none; } .menu{ display: none } .exit { z-index: 999; display: none; margin: 1.8rem; } .navbar .menu li { display: block; } .navbar .menu li a { display: inline-block; margin: 20px 0; font-size: 35px; } }
 <nav class="navbar" id="nav"> <div class="max-width"> <div class="logo"><a id="headSpan" href="index.html">Port<span>folio.</span></a></div> <ul class="menu"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Skills</a></li> <li><a href="#">Projects</a></li> <li><a href="#">CV</a></li> <li><a href="#">Contact</a></li> </ul> <div> <i class="fa fa-bars menuBtn" id="menuBtn" aria-hidden="true"></i> </div> <div class="exit"> <i class="fa fa-times-circle exit" id="exitBtn" aria-hidden="true"></i> </div> </div> </nav>

How do I make it work ? I tested to see if the add event listener was working and it was working but when it comes to displaying the menu when clicked it does not work. Any idea what the issue may be ? I am not that good at using Javascript so any help would be appreciated . Thank you

document.getElementsByClassName('menu'); doesn't return a single element. It returns anHTMLCollection . So menu isn't an element and menu.style.display = 'block doesn't do what you're trying to do.

document.getElementsByClassName('menu') gets multiple elements, all of which have the class 'menu' . The function returns an HTMLCollection, but you can treat it like a list. If you want to use classes, I would recommend using:

var list = document.getElementsByClassName('menu')
for (var item of list) {
    // Do Stuff Here
}

If you have multiple menus, consider using JQuery with the .each(function) method for functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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