响应式头部菜单转侧边栏切换功能失效问题排查
Hey there! As a fellow developer, I get how frustrating it is when a simple toggle feature doesn’t work—especially when you’ve already put in the work on HTML and CSS. Let’s break down why your menu isn’t showing up when you click that hamburger icon, and fix it step by step.
The Core Problem: CSS Specificity
The main issue stopping your toggle from working is CSS specificity (the rules that determine which styles take precedence).
In your media query for screens under 900px, you’ve set:
#nav-menu { right: -100%; /* other styles */ }
And your toggle class is:
.show-nav { right: 0; }
Since #nav-menu is an ID selector (higher specificity) and .show-nav is a class selector (lower specificity), the right: -100% from the ID will always override the right: 0 from the class—even when you add the class with JavaScript.
Quick Fix for the Toggle Function
Update your CSS to use a combined selector that has higher specificity than the ID alone. Change the .show-nav rule in your media query to:
#nav-menu.show-nav { right: 0; }
This combines the ID and class selector, making its specificity high enough to override the original #nav-menu styles.
Bonus: Fix Invalid HTML (Avoid Future Headaches)
I noticed you’re reusing the same ID (#nav and #link) multiple times in your HTML. IDs must be unique on a page—repeating them can cause unexpected behavior in JavaScript and CSS later on. Let’s fix that:
1. Replace repeated IDs with classes
Change your HTML from:
<div id="nav"><li><a id="link" href="#about-me">01. Sobre mim</a></li></div>
To:
<div class="nav"><li><a class="link" href="#about-me">01. Sobre mim</a></li></div>
Do this for all instances of #nav and #link.
2. Update your CSS to match the classes
Modify the corresponding CSS rules:
/* Replace #nav with .nav */ .nav { margin: auto 30px; } @media only screen and (max-width: 900px) { .nav { text-align: center; margin: 20px auto; } } /* Replace #link with .link */ .link { margin-right: 15px; color: white; text-decoration: none; transition: color 0.15s; } .link:hover { color: gray; }
Final Check
Your JavaScript function is actually correct—once you fix the CSS specificity and invalid HTML, clicking the hamburger icon should toggle the show-nav class and slide your sidebar into view.
Give these changes a try, and your responsive menu should work as expected!
内容的提问来源于stack exchange,提问作者user20676816

