简体   繁体   中英

JS - How to toggle a CSS class only if it alerady has been toggled

I'm trying to build my own responsive mobile navigation. This is my first attempt but I've got pretty far. It works but I have a problem with proper toggling.

This is my code:

  function classToggle() { var navigation = document.querySelectorAll('.nav-links') navigation.forEach(nav => nav.classList.toggle('mobile-navigation')); } document.querySelector('.menu-toggle-button').addEventListener('click', classToggle); document.querySelector('.nav-links').addEventListener('click', classToggle); 
 nav { display: flex; position: absolute; width: 100%; padding: 1rem 2rem; } .nav-links { display: none; } .nav-links li { text-align: center; list-style-type: none; margin: 1.7em 0 0 0; padding: 0 } nav, .nav-links { flex-direction: column; } .menu-toggle-button { align-self: flex-end; position: absolute; margin-top: 1rem; cursor: pointer; } .mobile-navigation { display: flex; justify-content: center; background-color: black; margin: 0; padding: 0; position: absolute; top: 0; left: 0; width: 100vw; height: 100vh; } @media (min-width: 992px) { /* Navigation */ .mobile-navigation { flex-direction: row; } .nav-links { display: flex; margin-left: auto; height: auto; padding: 0; } .nav-links, nav { flex-direction: row; } .nav-links li { margin-top: 0; margin-left: 2.6em; } .menu-toggle-button { display: none; } 
 <nav class="navbar"> <div class="brand"> <p>Logo</p> </div> <div class="menu-toggle-button"> <span>|||</span> </div> <ul class="nav-links"> <li> <a href="javascript:void(0)">Risus Baulits</a> </li> <li> <a href="javascript:void(0)">Sodales Vapien</a> </li> <li> <a href="javascript:void(0)">Fermentum</a> </li> <li> <a href="javascript:void(0)">Posuere Risus!</a> </li> </ul> </nav> 

https://codepen.io/anon/pen/MzJOrG

What I don't understand is how to add the click event to the menu only if it already has a class mobile-navigation so the class won't be toggled on bigger screen when the menu is a simple row of links. I don't want to use jQuery.

Thank you.

The concept is use CSS media queryto show/Hide the toggle button depending on the viewport size(windows size), for instance:

//hide the toggle button
.menu-toggle-button {
  display: none
}
//show the toggle button if window size is less than 768 
@media only screen and (max-width: 768px) {
   display: block
}

in this way the button will not show on desktop as the click event also

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