(仅限 Chrome)我正在尝试在运行时修改与媒体查询相关的 CSSRules,但是,当我修改规则时,文档不会重新呈现。仅当媒体查询再次更改时,文档才会重新呈现。如果你看一下小提琴,你会注意到在加载时,元素是深色的,而它应该立即变成红色。有没有办法让文档使样式无效?
如果您将浏览器窗口移动得更小,您会看到样式更改成功,然后再次变大,这样媒体查询样式就会两次失效。
小提琴:http: //jsfiddle.net/QNgxk/3/
编辑:有时小提琴有效???哎呀
代码:
HTML
<div id="test">I SHOULD BE RED</div>
CSS
#test {
position: absolute;
width: 100%;
background-color: #333;
height: 50px;
}
@media screen and (min-width: 481px) {
#test {
width: 50%;
}
}
JS
var test = document.getElementById('test'); // get the element
var rules = window.getMatchedCSSRules(test); // get matched rules
var regexp = new RegExp('^#test'); // test the CSS rule explicit id
var matchedRule;
for (var i = rules.length - 1; i >= 0; i--) { // loop through rules and find the explicit one
var rule = rules[i];
if (rule.cssText.match(regexp)) {
matchedRule = rule;
break;
}
}
// now change the rule to have a background of red, and width 20%
if (matchedRule) {
matchedRule.style.setProperty('background-color', '#f00');
matchedRule.style.setProperty('width', '20%');
}