屏幕缩小后Navbar无法恢复正常显示问题求助
问题根源
点击汉堡按钮时,JS直接给#navbar设置了内联样式(如display: none或display: inline-block),内联样式优先级高于CSS媒体查询规则,导致屏幕放大到801px以上时,媒体查询里的display: inline-flex无法生效。
解决方案
- 使用CSS类控制Navbar的折叠状态,避免直接修改内联样式
- 监听窗口大小变化,屏幕宽度超过800px时重置Navbar状态,确保媒体查询样式正常生效
修改后的代码
CSS
.toggle-btn { width: 35px; position: absolute; right: 80px; top: 25px; display: none; } .toggle-btn span { display: inline-block; width: 100%; height: 2px; background-color: #fff; float: left; margin-bottom: 8px; } /* 新增折叠状态类 */ #navbar.active { display: inline-block; position: absolute; top: 75px; width: 100%; text-align: center; padding: 5px 0; background: orange; height: auto; } @media (max-width: 800px) { .toggle-btn { display: block; } #navbar { display: none; } #header { display: block; } } @media (min-width: 801px) { #navbar { display: inline-flex; width: 100%; justify-content: space-evenly; padding-left: 15%; align-self: center; height: 75px; align-items: center; } #header { display: inline-flex; } } #header { display: inline-flex; width: 100%; color: #fff; background-color: #000; height: 75px; } #navbar { display: inline-flex; width: 100%; justify-content: space-evenly; padding-left: 15%; align-self: center; height: 75px; align-items: center; }
JavaScript
const navbar = document.getElementById('navbar') let isOpen = false function toggleFunction() { isOpen = !isOpen navbar.classList.toggle('active', isOpen) } // 监听窗口大小变化,自动重置Navbar状态 window.addEventListener('resize', () => { if (window.innerWidth > 800) { isOpen = false navbar.classList.remove('active') } })
HTML(无需修改)
<div class="toggle-btn" onclick="toggleFunction()"> <span></span> <span></span> <span></span> </div> <nav id="header"> <img src="pantherlogo.png" alt="Beverly Panthers Logo" id="logo"> <div id="navbar"> <h3><a href="index.html">HOME</a></h3> <h3><a href="news.html">NEWS</a></h3> <h3><a href="team.html">TEAMS</a></h3> <h3><a href="history.html">HISTORY</a></h3> <h3><a href="contacts.html">CONTACTS</a></h3> </div> </nav> <div id="top"> <img src="footballimg.png" alt="football" id="footballimg"> <div id="motto"> <h1>Restore our pride.</h1> </div> </div>
内容的提问来源于stack exchange,提问作者Maddy Young
相关产品推荐
相关产品推荐

