简体   繁体   中英

Toggle of mobile menu not working properly

I am building a responsive navigation bar. The toggling of hide/show is working for mobile (max-width:699px) but when i increase the screen width, the links of navbar either is hidden or shows in block. I want whenever I increase the screen width, the nav should display in flex rather inheriting parent properties. Can anyone help me please.

 var span = document.querySelector("span"); var second = document.querySelector(".second"); span.addEventListener('click', function() { if (second.style.display === "none") { second.style.display = "flex"; } else { second.style.display = "none"; } });
 * { margin: 0; padding: 0; } nav { margin: auto; height: 500px; } nav ul { list-style-type: none; padding: 0; } nav a { text-decoration: none; padding: 10px; display: block; text-align: center; } nav span { display: block; right: 0; top: 0; position: absolute; padding: 10px; } .first a { text-align: left; } .first { overflow: hidden; position: relative; } .second { display: none; } @media screen and (min-width: 700px) { nav { display: flex; justify-content: space-between; } nav ul { display: flex; justify-content: space-between } nav span { display: none; } .second { display: flex; } }
 <nav> <ul class="first"> <li><a href="#">Heading</a></li> </ul> <ul class="second"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> <span> <i class="fas fa-bars"></i> </span> </nav>

You can achieve the behavior that you want by toggling a class that has the necessary styles attached to it. When you put the styles directly on the element those styles will be prioritized higher than the class based styling you have.

Add styling

.flex { display: flex; }

And use this Javascript

var span = document.querySelector("span");
var second = document.querySelector(".second");
span.addEventListener('click', function() {
  second.classList.toggle("flex")
});

Example codepen: https://codepen.io/danba340/pen/ZEOjozz

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