【问题标题】:@media screen in JavaScript?JavaScript 中的@media 屏幕?
【发布时间】:2019-08-21 07:10:12
【问题描述】:

我编写了这个脚本。如果窗口大小小于 1000 像素,则可以展开菜单点。 但是,如果您折叠菜单点并增加窗口大小,菜单点仍会保持隐藏状态。我不让它再次淡入它们。

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】:

    您的问题在于 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 等)并根据视口控制将应用哪个类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      相关资源
      最近更新 更多