You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中@media screen适配菜单窗口放大后无法恢复显示求助

Fix: Menu Doesn't Reappear When Resizing Window Back to Larger Than 1000px

I see the exact issue here—let’s break it down and fix it right away!

The core problem boils down to CSS specificity: when your fold() function toggles x.style.display, it adds inline styles directly to the #folding element. Inline styles have higher priority than regular CSS rules or media query styles. So even after you resize the window back to over 1000px, the inline display: none (from folding the menu) overrides the base CSS’s #folding { display: block; }.

Here are two reliable solutions to fix this:


Solution 1: Use CSS Classes (Cleanest, Most Maintainable Approach)

Instead of manipulating inline styles directly, toggle a CSS class to control visibility. This lets media queries properly override the class when the window size changes, since class specificity doesn’t beat media query rules for the same element.

Updated HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<nav>
<h2>S U P E R</h2>
<button class="button" onclick="fold()">FOLD</button>
<div id="folding">
<a>Under Construction 1</a><br>
<a>Under Construction 2</a><br>
<a>Under Construction 3</a><br>
<a>Under Construction 4</a><br>
</div>
</nav>
</body>
</html>

Updated CSS

#folding { display: block; }
.button { display: none; }
/* Custom class to handle hiding */
#folding.hidden { display: none; }

@media screen and (max-width: 1000px) {
.button { display: block; }
#folding { display: block; } /* Reset base state so the class can toggle */
body { background-color: red; }
}

Updated JS

function fold() {
  var x = document.getElementById("folding");
  x.classList.toggle("hidden"); // Toggle the class instead of inline styles
}

Solution 2: Listen for Window Resize Events

If you’d rather stick with inline styles, add a resize event listener to reset the menu’s display when the window grows beyond 1000px:

Updated JS

function fold() {
  var x = document.getElementById("folding");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}

// Add listener to reset menu on resize
window.addEventListener('resize', function() {
  var x = document.getElementById("folding");
  if (window.innerWidth > 1000) {
    x.style.display = "block"; // Force menu to show when window is large enough
  }
});

Either solution will fix your issue: when you resize back to a window wider than 1000px, the menu will automatically reappear even if you folded it earlier. The class-based approach is preferred because it keeps styling logic in CSS where it belongs, making your code easier to update later.

内容的提问来源于stack exchange,提问作者user5513378

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:39:41