如何正确使用CSSStyleSheet.insertRule()?

时间:2015-03-08 19:22:32

标签: javascript css stylesheet

我无法弄清楚我在哪里出错:/。当我运行此代码时,我得到的只是一个空白元素。我似乎无法使用insertRule方法做任何事情(甚至不会产生错误)。我错过了什么吗?

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
<script>
    var sheet = (function() {
        // Create the <style> tag
        var style = document.createElement("style");

        // WebKit hack
        style.appendChild(document.createTextNode(""));

        // Add the <style> element to the page
        document.head.appendChild(style);

        return style.sheet;
    })();
    sheet.insertRule("\
        #gridContainer {\
            width: 100%;\
            height: 100%;\
        }\
    ", 0);
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:13)

这有点令人困惑,但您的代码确实有效,只是您无法在返回的XML树中看到插入的规则。

要验证您的代码是否有效,您可以执行两项测试:

&#13;
&#13;
var style = (function() {
    // Create the <style> tag
    var style = document.createElement("style");

    // WebKit hack
    style.appendChild(document.createTextNode(""));

    // Add the <style> element to the page
    document.head.appendChild(style);
  
    console.log(style.sheet.cssRules); // length is 0, and no rules

    return style;
})();
style.sheet.insertRule('.foo{color:red;}', 0);
console.log(style.sheet.cssRules); // length is 1, rule added
&#13;
<p class="foo">
  I am some text
</p>
&#13;
&#13;
&#13;

运行上面的代码段,您可以看到CSS规则确实适用。 cssRules属性也会在控制台中发生变化。

当浏览器扩展生成附加到DOM的自定义样式表时,通常会注意到这一点,并且在调试时它们在检查器中显示为空样式表。

答案 1 :(得分:1)

此版本基于Awal的回答和Totally Pwn CSS以及来自web archive的Javascript。 id 参数对于使用getElementById访问styleSheet非常有用, media 参数是optinal并且默认为&#39; screen&#39;。 我正在返回 styleSheet.sheet ,这只是我的偏好。

function createStyleSheet (id, media) {
    var el   = document.createElement('style');
    // WebKit hack
    el.appendChild(document.createTextNode(''));
    el.type  = 'text/css';
    el.rel   = 'stylesheet';
    el.media = media || 'screen';
    el.id    = id;
    document.head.appendChild(el);
    return el.sheet;
}