Can I change the media query using javascript / jQuery?

前端 未结 7 954
逝去的感伤
逝去的感伤 2020-12-10 15:50

I have a style.css with a media query. In my javascript-file, I have a value for the desired mobile-width stored in a variable.

By changing the variable, I want to c

7条回答
  •  天涯浪人
    2020-12-10 16:21

    The best option would be to have two sets of media queries which are only applied based on a parent class being present.

    @media (max-width: 600px) {
    
      .w600 .myDiv{
        color:red;
      }
    
    }
    
    @media (max-width: 400px) {
    
      .w400 .myDiv{
        color:red;
      }
    
    }
    

    You could then add/remove w600 or w400 to the body class to allow the required media query to work.

    Using jQuery this could be done like:

    $("body").addClass("w600")
             .removeClass("w400");
    

    I appreciate you may have more than just one style and would therefore like to reduce code duplication.

    In which case you could use a CSS transpiler such as Less with mixins:

    @mediaqueryruleset:{
      .myDiv{
        color:red;
      }
      .myOtherDiv{
        color:blue;
      }
    }
    
    @media (max-width: 600px) {
    
      .w600 {
        @mediaqueryruleset();
      }
    
    }
    
    @media (max-width: 400px) {
    
      .w400 {
        @mediaqueryruleset();
      }
    
    }
    

    Which would output:

    @media (max-width: 600px) {
      .w600 .myDiv {
        color: red;
      }
      .w600 .myOtherDiv {
        color: blue;
      }
    }
    @media (max-width: 400px) {
      .w400 .myDiv {
        color: red;
      }
      .w400 .myOtherDiv {
        color: blue;
      }
    }
    

提交回复
热议问题