我正在寻找一种方法,将一个<style>标签插入到一个HTML页面与JavaScript。

目前为止我发现的最好的方法是:

var divNode = document.createElement("div");
divNode.innerHTML = "<br><style>h1 { background: red; }</style>";
document.body.appendChild(divNode);

这适用于Firefox, Opera和Internet Explorer,但不适用于谷歌Chrome。而且,对于IE来说,前面的<br>有点难看。

有人知道如何创建<style>标签吗

是更好的 工作与Chrome?

或者

这是我应该避免的不规范的事情 三个可用的浏览器都很棒,谁会用Chrome呢?


当前回答

下面是一个脚本,它将ie风格的createStyleSheet()和addRule()方法添加到没有它们的浏览器中:

if(typeof document.createStyleSheet === 'undefined') {
    document.createStyleSheet = (function() {
        function createStyleSheet(href) {
            if(typeof href !== 'undefined') {
                var element = document.createElement('link');
                element.type = 'text/css';
                element.rel = 'stylesheet';
                element.href = href;
            }
            else {
                var element = document.createElement('style');
                element.type = 'text/css';
            }

            document.getElementsByTagName('head')[0].appendChild(element);
            var sheet = document.styleSheets[document.styleSheets.length - 1];

            if(typeof sheet.addRule === 'undefined')
                sheet.addRule = addRule;

            if(typeof sheet.removeRule === 'undefined')
                sheet.removeRule = sheet.deleteRule;

            return sheet;
        }

        function addRule(selectorText, cssText, index) {
            if(typeof index === 'undefined')
                index = this.cssRules.length;

            this.insertRule(selectorText + ' {' + cssText + '}', index);
        }

        return createStyleSheet;
    })();
}

您可以通过添加外部文件

document.createStyleSheet('foo.css');

动态创建规则

var sheet = document.createStyleSheet();
sheet.addRule('h1', 'background: red;');

其他回答

据我所知,有4种方法。

var style= document.createElement("style");
(document.head || document.documentElement).appendChild(style);
var rule=':visited {    color: rgb(233, 106, 106) !important;}';

//no 1
style.innerHTML = rule;
//no 2
style.appendChild(document.createTextNode(rule));

//no 3 limited with one group
style.sheet.insertRule(rule);
//no 4 limited too
document.styleSheets[0].insertRule('strong { color: red; }');

//addon
style.sheet.cssRules //list all style
stylesheet.deleteRule(0)  //delete first rule

通常情况下,需要重写现有的规则,因此向HEAD添加新样式并不适用于所有情况。

我想出了这个简单的函数,它总结了所有无效的“追加到BODY”方法,只是更方便使用和调试(IE8+)。

window.injectCSS = (function(doc){
    // wrapper for all injected styles and temp el to create them
    var wrap = doc.createElement('div');
    var temp = doc.createElement('div');
    // rules like "a {color: red}" etc.
    return function (cssRules) {
        // append wrapper to the body on the first call
        if (!wrap.id) {
            wrap.id = 'injected-css';
            wrap.style.display = 'none';
            doc.body.appendChild(wrap);
        }
        // <br> for IE: http://goo.gl/vLY4x7
        temp.innerHTML = '<br><style>'+ cssRules +'</style>';
        wrap.appendChild( temp.children[1] );
    };
})(document);

演示:codepen, jsfiddle

试着把风格元素添加到头部而不是身体。

在IE(7-9)、Firefox、Opera和Chrome中进行了测试:

var css = 'h1 { background: red; }',
    head = document.head || document.getElementsByTagName('head')[0],
    style = document.createElement('style');

head.appendChild(style);

style.type = 'text/css';
if (style.styleSheet){
  // This is required for IE8 and below.
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}

一切都好,除了styleNode。要在IE6中使用javascipt创建的节点工作,您需要在设置cssText之前将节点附加到文档中;

更多信息@ http://msdn.microsoft.com/en-us/library/ms533698%28VS.85%29.aspx

当你像这样调用appendStyle函数时,这个函数会注入css: appendStyle('你想要注入的css ')

这是通过向文档头部注入样式节点来实现的。这与通常用于延迟加载JavaScript的技术类似。 它在大多数现代浏览器中始终如一地工作。

appendStyle = function (content) { style = document.createElement('STYLE'); style.type = 'text/css'; style.appendChild(document.createTextNode(content)); document.head.appendChild(style); } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h1>Lorem Ipsum</h1> <p>dolar sit amet</p> <button onclick='appendStyle("body { background-color: #ff0000;}h1 { font-family: Helvetica, sans-serif; font-variant: small-caps; letter-spacing: 3px; color: #ff0000; background-color: #000000;}p { font-family: Georgia, serif; font-size: 14px; font-style: normal; font-weight: normal; color: #000000; background-color: #ffff00;}")'>Press me to inject CSS!</button> </body> </html>

你也可以使用下面的代码片段惰性加载外部CSS文件:

appendExternalStyle = function (content) { link = document.createElement('LINK'); link.rel = 'stylesheet'; link.href = content; link.type = 'text/css'; document.head.appendChild(link); } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> html { font-family: sans-serif; font-display: swap; } </style> </head> <body> <h1>Lorem Ipsum</h1> <p>dolar sit amet</p> <button onclick='appendExternalStyle("data:text/css;base64,OjotbW96LXNlbGVjdGlvbntjb2xvcjojZmZmIWltcG9ydGFudDtiYWNrZ3JvdW5kOiMwMDB9OjpzZWxlY3Rpb257Y29sb3I6I2ZmZiFpbXBvcnRhbnQ7YmFja2dyb3VuZDojMDAwfWgxe2ZvbnQtc2l6ZToyZW19Ym9keSxodG1se2NvbG9yOnJnYmEoMCwwLDAsLjc1KTtmb250LXNpemU6MTZweDtmb250LWZhbWlseTpMYXRvLEhlbHZldGljYSBOZXVlLEhlbHZldGljYSxzYW5zLXNlcmlmO2xpbmUtaGVpZ2h0OjEuNjd9YnV0dG9uLGlucHV0e292ZXJmbG93OnZpc2libGV9YnV0dG9uLHNlbGVjdHstd2Via2l0LXRyYW5zaXRpb24tZHVyYXRpb246LjFzO3RyYW5zaXRpb24tZHVyYXRpb246LjFzfQ==")'>press me to inject css!</button> </body> </html>