【问题标题】:Can I change the media query using javascript / jQuery?我可以使用 javascript / jQuery 更改媒体查询吗?
【发布时间】:2021-12-04 02:34:00
【问题描述】:

我有一个带有媒体查询的 style.css。在我的 javascript 文件中,我有一个存储在变量中的所需移动宽度的值。

通过更改变量,我想自动更改媒体查询的值。是否有可能用javascript改变.css文件的内容,就像我可以改变DOM一样? 使用 javascript 向 DOM 添加 HTML <style>-element 不是我想要的解决方案,因为我想将所有 css 保留在 .css 文件中

【问题讨论】:

  • 不,这不可能。为什么不为不同的宽度编写不同的媒体查询?
  • 据我所知,不,你不能。但是,您可以做的是通过 javascript 在目标元素上添加或删除 css 类。
  • 可以使用window.matchMedia()来检测JS中媒体查询的任何变化
  • @asprin “据我所知,不,你不能。” 可以通过设置.media.mediaTextdocument.styleSheets[0].cssRules plnkr.co/edit/qzLO5J4KlWZLQnjMIy7i?p=preview 来实现

标签: javascript jquery html css


【解决方案1】:

是的。可能是。灵感来自 @guest271314 answer。这似乎允许通过 JavaScript 更改媒体查询条件。

document.styleSheets[0].cssRules[0].conditionText = "(min-width: 0px)";

当然,检查规则是否应用了媒体查询:

var currentQuery = {index:0,rule:null,mediaText:null};
var inclusionQuery = "(min-width: 0px)";
var exclusionQuery = "(min-width: 99999px)";
var numberOfMediaQueries = 0;

function hideAllMediaQueries() {
    var rules = document.styleSheets[0].cssRules;
    var firstQueryIndex = 0; // show this query
    var queryIndex = 0;
    var numberOfRules = rules!=null ? rules.length : 0;

    // loop through rules and hide media queries except selected
    for (var i=0;i<numberOfRules;i++) {
        var rule = rules[i];

        if (rule.media!=null) {

            if (queryIndex==firstQueryIndex) {
                currentQuery.mediaText = rule.conditionText;
                currentQuery.index = firstQueryIndex;
                currentQuery.rule = rule;
                rule.conditionText = inclusionQuery;
            }
            else {
                rule.conditionText = exclusionQuery;
            }

            queryIndex++;
        }
    }

    numberOfMediaQueries = queryIndex;
}

注意:上面的示例仅适用于 CSS 中现有的媒体查询。它不会添加或删除查询。它通过检查rule.media 属性不为空来检查媒体查询是否存在。

【讨论】:

    【解决方案2】:

    最好的选择是有两组媒体查询,它们仅根据存在的父类应用。

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

    然后您可以将w600w400 添加/删除到body 类以允许所需的媒体查询工作。

    使用 jQuery 可以这样做:

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

    感谢您可能不止一种风格,因此希望减少代码重复。

    在这种情况下,您可以使用带有 mixins 的 CSS 转译器,例如 Less

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

    哪个会输出:

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

    【讨论】:

    • @Curt "您不能在 CSS 文件中动态更改媒体查询变量(无需通过 javascript 再次注入整个样式表" 可以使用 @ 动态更改媒体查询变量987654330@ document.styleSheet .cssRules plnkr.co/edit/qzLO5J4KlWZLQnjMIy7i?p=preview
    • @guest271314 谢谢,我不知道你可以这样做。但是,我仍然不建议将其作为可行的选择。样式表/媒体查询的顺序有很多依赖关系。
    【解决方案3】:

    您可以直接使用.media.mediaTextdocument.styleSheets[0].cssRules 设置规则

    document.styleSheets[0].cssRules[0].media.mediaText = /* new media rule here */;
    

    plnkrhttp://plnkr.co/edit/qzLO5J4KlWZLQnjMIy7i?p=preview

    【讨论】:

    • 设置该属性时出错,Error: Permission denied to access property "mediaText",但我可以设置conditionTextdocument.styleSheets[0].cssRules[0].conditionText = "(min-width: 0px)";
    • 请注意,由于 CORS 安全策略stackoverflow.com/questions/49993633/…,这可能会失败
    【解决方案4】:

    您可以使用Enquire.js jQuery 插件。

    它是一个 JavaScript 库,用于处理 JavaScript 中的媒体查询。

    这是快速入门代码示例:

    enquire.register("screen and (max-width:45em)", {
    
        // OPTIONAL
        // If supplied, triggered when a media query matches.
        match : function() {},      
    
        // OPTIONAL
        // If supplied, triggered when the media query transitions 
        // *from a matched state to an unmatched state*.
        unmatch : function() {},    
    
        // OPTIONAL
        // If supplied, triggered once, when the handler is registered.
        setup : function() {},    
    
        // OPTIONAL, defaults to false
        // If set to true, defers execution of the setup function 
        // until the first time the media query is matched
        deferSetup : true,
    
        // OPTIONAL
        // If supplied, triggered when handler is unregistered. 
        // Place cleanup code here
        destroy : function() {}
    
    });
    

    【讨论】:

      【解决方案5】:

      你可以写$(window).width()

      value=959;
      
      if($(window).width() < value)
      {
          $(".classname").css("color","white");
      }
      

      【讨论】:

      • 是的,但由于媒体查询中有数百个值,我需要在 javascript 中进行数百个 css 更改。我可以说像 $(MEDIAQUERY).maxWidth(variableValue); 这样的话吗? ?
      猜你喜欢
      • 1970-01-01
      • 2021-02-27
      • 2021-05-31
      • 1970-01-01
      • 2019-08-14
      • 2017-04-06
      • 2013-07-29
      • 2017-06-21
      相关资源
      最近更新 更多