我能使用JavaScript / jQuery 更改媒体查询吗?

14

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

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


不,这是不可能的。为什么不为不同的宽度编写不同的媒体查询呢? - steo
4
据我所知,不可以直接实现您想要的功能。但是,您可以通过JavaScript在目标元素上添加或删除CSS类。 - asprin
1
你可以使用 window.matchMedia() 在JS中检测媒体查询的任何变化。 - Vishnu Shekhawat
1
据我所知,不可以。但是通过设置 document.styleSheets [0] .cssRules.media.mediaText属性是可能的。http://plnkr.co/edit/qzLO5J4KlWZLQnjMIy7i?p=preview - guest271314
5个回答

9
最好的选择是有两组媒体查询,只基于一个父类存在而应用。
@media (max-width: 600px) {

  .w600 .myDiv{
    color:red;
  }

}

@media (max-width: 400px) {

  .w400 .myDiv{
    color:red;
  }

}

你可以通过将 w600w400 添加/删除到 body 类中来允许所需的媒体查询起作用。
使用 jQuery,可以这样做:
$("body").addClass("w600")
         .removeClass("w400");

我很理解你可能有不止一种风格,因此想要减少代码重复。

在这种情况下,你可以使用CSS转译器,比如Less与mixin:

@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;
  }
}

1
@Curt_"你不能在CSS文件中动态更改媒体查询变量(除非通过JavaScript再次注入整个样式表)"。可以使用document.styleSheet .cssRules.media.mediaText来动态更改媒体查询变量。http://plnkr.co/edit/qzLO5J4KlWZLQnjMIy7i?p=preview - guest271314
谢谢@guest271314,我不知道你可以这样做。然而,我仍然不建议它作为可行的选项。样式表/媒体查询的顺序有很多依赖关系。 - Curtis

6
您可以直接使用document.styleSheets [0] .cssRules的 .media.mediaText 来设置规则。
document.styleSheets[0].cssRules[0].media.mediaText = /* new media rule here */;

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

该文本中包含一个链接,指向名为"plnkr"的网站,并提供了一个代码示例。

设置该属性时出现错误,Error: Permission denied to access property "mediaText",但我可以设置 conditionTextdocument.styleSheets[0].cssRules[0].conditionText = "(min-width: 0px)"; - 1.21 gigawatts
2
请注意,由于CORS安全策略,此操作可能会失败。https://dev59.com/HlUL5IYBdhLWcg3wqpk7 - Jacob C.

1
您可以通过使用$(window).width()来编写。
value=959;

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

是的,但由于该媒体查询中有数百个值,我需要在JavaScript中进行数百个CSS更改。我能否像$(MEDIAQUERY).maxWidth(variableValue);这样说? - Skalibran

0

你可以使用Enquire.jsjQuery插件。

这是一个用于处理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() {}

});

0

是的,可能吧。受到 @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 属性是否为 null 来检查媒体查询是否存在。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接