简体   繁体   English

JS-仅在切换类的情况下如何切换CSS类

[英]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 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. 我不明白的是如何仅在类已经具有移动导航功能的情况下才将click事件添加到菜单,因此当菜单是简单的链接行时,不会在更大的屏幕上切换类。 I don't want to use jQuery. 我不想使用jQuery。

Thank you. 谢谢。

The concept is use CSS media queryto show/Hide the toggle button depending on the viewport size(windows size), for instance: 这个概念是使用CSS媒体查询根据视口大小(窗口大小)显示/隐藏切换按钮,例如:

//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 这样,该按钮将不会在桌面上显示为click事件,

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

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