JavaScript中的@media屏幕?

问题描述 投票:1回答:1

我编写了这个脚本。如果窗口大小小于1000px,则可以展开菜单点。但是,如果您折叠菜单点并增加窗口大小,菜单点仍然保持隐藏状态。我再也不让它褪色了。

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>

CSS:

#folding {
display: block;
}
.button {
display: none;
}
@media screen and (max-width: 1000px) {
.button {
display: block;
} 
#folding {
display: none;
}
body {
background-color: red;
}
}

JS:

function fold() {
  var x = document.getElementById("folding");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}
javascript css mobile media-queries screen
1个回答
2
投票

你的问题是css特异性(见Specificity)。实现目标的一个简单而快速的解决方案是反转媒体逻辑并对属性应用重要内容以覆盖内联规则display:none;

.button {
  display: block;
}
#folding {
  display: none;
}

@media screen and (min-width: 1000px) {
 #folding {
  display: block !important;
 }
 .button {
  display: none;
 }
}

当你执行x.style.display = "none";时,你会添加一个内联样式,它具有针对类和id样式的优先级。你做你想做的最好的方法是创建不同的类(.folding-visible等...)并根据视口控制将应用哪个类。

© www.soinside.com 2019 - 2024. All rights reserved.