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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28930846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:47:09  来源:igfitidea点击:

How to use CSSStyleSheet.insertRule() properly?

javascriptcssstylesheet

提问by klinore

I can't figure out where I'm going wrong here :/. When I run this code, all I get is a blank element. I can't seem to get the insertRule method to do anything (not even produce an error). Am I missing something?

我不知道我哪里出错了:/。当我运行这段代码时,我得到的只是一个空白元素。我似乎无法让 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>

回答by user3459110

It is slightly confusing but your code does actually work, it is just that you can't see the inserted rules in the XML tree returned.

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

To verify that your code works, there are two tests you can do:

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

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
<p class="foo">
  I am some text
</p>

Run the above snippet, and you can see that the CSS rule does apply. And the cssRulesproperty changes as well in the console.

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

This is often noted when browser extensions generate custom style-sheets appended to the DOM, and while debugging they appear as empty style-sheets in the inspector.

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

回答by Jorge Gonzalez

This version is based on Awal's answer and Totally Pwn CSS with Javascript from web archive. The idparameter is useful for accesing the styleSheet with getElementById, and the mediaparameter is optinal and defauts to 'screen'. I am returning the styleSheet.sheet, this is just my preference.

此版本基于 Awal 的回答和 Totally Pwn CSS with Javascript from web archive。该ID参数是用的getElementById accesing样式表是有用的,而媒体的参数是optinal和defauts为“屏幕”。我正在返回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;
}