javascript - 强制文档在 CSSStyleDeclaration 更新时重新渲染(chrome)

标签 javascript css google-chrome media-queries

(仅限 CHROME)我试图在运行时修改媒体查询相关的 CSSRules,但是,当我修改规则时,文档不会重新呈现。只有当媒体查询再次更改时,文档才会重新呈现。如果你看一下 fiddle ,你会注意到在加载时,元素是深色的,而它应该立即是红色的。有没有办法让文档使样式无效?

如果您将浏览器窗口移动得更小然后再变大,您会看到样式已成功更改,这样它会使媒体查询样式两次无效。

fiddle :http://jsfiddle.net/QNgxk/3/

编辑:有时 fiddle 奏效了???哎呀

代码:

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

最佳答案

我有一个类似的问题,我只是在这里写这篇文章以防它可能对其他人有帮助。 对我来说,匹配规则的测试是不正确的。在 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");

希望这对您有所帮助。

关于javascript - 强制文档在 CSSStyleDeclaration 更新时重新渲染(chrome),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14509128/

相关文章:

javascript - 使用 jquery 制作 div 动画

javascript - 测试浏览器扩展

reactjs - 永远显示 "lighthouse is warming up"

css - 矛盾的CSS规则 `.myClass:hover { display:none; }`没有效果

html - 使用 CSS 自定义 HTML <select>

jquery - Chrome 缓存快把我逼疯了

javascript - 使用 javascript 或 jquery 提交链接,无需刷新页面

javascript - jQuery 中 val.length 和 val().length 的区别?

html - css 背景颜色随文档类型消失

html - 如何将倾斜的 div 停靠到上面的 div?