@media 屏幕在 JavaScript?
@media screen in JavaScript?
我编写了这个脚本。如果window尺寸小于1000px,可以展开菜单点。
但是,如果折叠菜单点并增加 window 大小,菜单点仍会隐藏。我不知道它会再次淡入淡出。
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";
}
}
您的问题是 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";
时,您正在添加优先于 classes 和 id 样式的内联样式。做你想做的最好的方法是创建不同的 classes(.folding-visible 等)并根据视口控制将应用哪个 class。
我编写了这个脚本。如果window尺寸小于1000px,可以展开菜单点。 但是,如果折叠菜单点并增加 window 大小,菜单点仍会隐藏。我不知道它会再次淡入淡出。
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";
}
}
您的问题是 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";
时,您正在添加优先于 classes 和 id 样式的内联样式。做你想做的最好的方法是创建不同的 classes(.folding-visible 等)并根据视口控制将应用哪个 class。