【问题标题】:How to change a css class property value for a specific mediaquery?如何更改特定媒体查询的 CSS 类属性值?
【发布时间】:2020-02-04 21:31:36
【问题描述】:

我有课

.foo {
  width: 30px;
}
@media only screen and (max-width:768px){
   .foo {
     width: 20px;
   }
}

我想用javascript将宽度的值从20px更改为15px,仅用于媒体查询。 当我这样做时,它会更改所有分辨率的类,以减少 CSS 中的媒体查询。

【问题讨论】:

标签: javascript html css media-queries


【解决方案1】:

你可以试试这个:

if (window.matchMedia("(max-width: 768px)").matches) {
  document.querySelector('.foo').style.width = "15px";
}

【讨论】:

    【解决方案2】:

    我建议为此分辨率在 CSS 中创建一个单独的类,并在需要时将此样式添加到该标记:

          if (window.matchMedia("(max-width: 768px)").matches) {
              document.querySelector('.foo').classList.Add("newClass"); }
    

    【讨论】:

      【解决方案3】:

      您无法更改媒体查询 css,但您可以创建 css 属性,并使用 javascript 设置该属性。

      这样只会影响媒体查询中的css。

      const foo = document.querySelector('.foo');
      
      setTimeout(() => {
        // This doesn't affect anything if the window width is above 768px
        foo.style.setProperty('--mobile-width', '15px');
      }, 2000);
      .foo {
        width: 30px;
        background-color: salmon;
        
        --mobile-width: 20px;
      }
      
      @media only screen and (max-width:768px){
         .foo {
           width: var(--mobile-width);
         }
      }
      <div class="foo">Foo</div>

      【讨论】:

      • 感谢您的回答!我考虑过这一点,但我需要设置的值不在一组常量中。它可以是任何整数。我将在下面解释我做了什么。
      【解决方案4】:

      我做了什么来解决这个问题。我在 matchMedia 上使用了一个侦听器,每次浏览器超过限制时,我都会运行一个 JS 例程来设置我的元素中的值(由 css 类名找到)。 这样,它就像媒体查询一样工作,但变化的值可以是任何东西。

                      var w = 50; // Can change
                      // media query event handler
                      if (matchMedia) {
                          const mq = window.matchMedia("(max-width:768px)");
                          mq.addListener(WidthChange);
                          WidthChange(mq);
                      }
      
                      function WidthChange(mq) {
                          if (mq.matches) {
      
                              // window width is less than 768px
                              changeFoo('foo', 20);
      
      
                          } else {
      
                              // window width is at least 768px
      
                              changeFoo('foo', w);
      
                          }
                      }
      
      
                     function changeFoo(aClass, value) {
                              var c = document.getElementsByClassName(aClass);
                              for(i=0; i < c.length; i++) {
                                c[i].style.width = value + 'vw';
                              }
                     }
      
      

      【讨论】:

        猜你喜欢
        • 2010-10-22
        • 1970-01-01
        • 1970-01-01
        • 2018-02-13
        • 2022-07-07
        • 2019-08-14
        • 1970-01-01
        • 1970-01-01
        • 2022-08-08
        相关资源
        最近更新 更多