【问题标题】:Is it possible to only trigger a media query if a certain variable is a certain value?如果某个变量是某个值,是否可以只触发媒体查询?
【发布时间】:2023-01-12 12:55:40
【问题描述】:

如果屏幕尺寸低于 1000px 且变量大于 15,我试图从我的窗口中删除一个元素。

我有我的 CSS 文件:

@media (max-width: 1000px){
  #specific-id{
     display:none
   }
}

但我只希望在变量大于 15 时发生这种情况。如何对此实现 javascript 控制?

【问题讨论】:

  • 您可以让 javascript 根据该条件有条件地向元素添加/删除类
  • 您要解决的根本问题是什么?正如@Nick 指出的那样,您可以根据变量值在 html 元素上切换类
  • 我有一个变量,它根据变量的编号更改容器的大小。所以当变量太高而屏幕尺寸太小时,我想从屏幕上移除容器。编辑:增加变量值会增加容器大小

标签: javascript html css media-queries


【解决方案1】:

我想你可以使用你可以尝试的自定义媒体查询

下面是文档中的一个实现示例:

Define a map of names to values for JS. Values can be either a MediaQueryList object or a boolean, in which case it’s treated identically to the above, or can be a number or a string, in which case it’s treated like a normal MQ, and can use the normal or range context syntax. Like:

<script>
CSS.customMedia.set('--foo', 5);
</script>
<style>
@media (_foo: 5) { ... }
@media (_foo < 10) { ... }
</style>

文档链接:https://www.w3.org/TR/mediaqueries-5/#custom-mq

【讨论】:

    【解决方案2】:

    我认为最好的方法是添加一个仅在变量大于 15 时才添加的类:

    如果变量小于 15:

    const variable = 0
    const specificId = document.getElementById('specific-id')
    
    if (variable > 15) {
      specificId.classList.add("variableIsMoreThan15")
    }
    #specific-id {
      background: red;
    }
    
    @media (max-width: 1000px){
      .variableIsMoreThan15 {
         display:none
       }
    }
    <div id="specific-id">
    Hello
    </div>

    如果变量大于 15:

    const variable = 16
    const specificId = document.getElementById('specific-id')
    
    if (variable > 15) {
      specificId.classList.add("variableIsMoreThan15")
    }
    #specific-id {
      background: red;
    }
    
    @media (max-width: 1000px){
      .variableIsMoreThan15 {
         display:none
       }
    }
    <div id="specific-id">
    Hello
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      • 2019-09-19
      • 1970-01-01
      • 2011-12-01
      • 2015-04-07
      • 2020-05-12
      • 1970-01-01
      相关资源
      最近更新 更多