【问题标题】:Forcing document re-render upon CSSStyleDeclaration update (chrome)在 CSSStyleDeclaration 更新时强制文档重新渲染(chrome)
【发布时间】:2013-01-08 16:02:41
【问题描述】:

(仅限 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%');
}

【问题讨论】:

    标签: javascript css google-chrome media-queries


    【解决方案1】:

    我遇到了类似的问题,我只是在这里写这个,以防它可能对其他人有所帮助。 对我来说,匹配规则的测试是不正确的。在 FireFox 中,它的作用与 selectorText 一样,因为它是在样式表中编写的,但 Chrome 会将所有名称转换为小写。所以这个测试在 Chrome 中是不匹配的:

    if(theRules[i].selectorText == ".myRule pre"){
    

    在 FireFox 中会匹配,但 Chrome 将选择器文本更改为小写,因此:

    .myrule pre
    

    所以把代码改成这样:

    if(theRules[i].selectorText.toLowerCase() == ".codemirror pre"){
    

    修复了这个问题,使其在两种浏览器中都可以使用。顺便说一句,setProperty 在 Chrome 30 中对我有用。我使用它的原因是因为它允许指定重要的:

    theRules[i].style.setProperty("font-size", this.editorFontSize+"px", "important");
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 2014-04-20
      • 2017-05-08
      • 2017-11-13
      相关资源
      最近更新 更多