如何创建< style>标签与Javascript

问题描述:

我在寻找一种方法来插入< style>

I'm looking for a way to insert a <style> tag into an HTML page with javascript.

到目前为止,我发现的最佳方式是:

The best way I found so far:

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

这可以在Firefox,Opera和Internet Explorer中使用,但不能在Google Chrome中使用。也有一个有点丑的< br>在前面的IE。

This works in Firefox, Opera and Internet Explorer but not in Google Chrome. Also it's a bit ugly with the <br> in front for IE.

有没有人知道一个方法来创建一个< style>

Does anyone know of a way to create a <style> tag that


  1. 更好用

  2. 适用于Chrome?

或者


  1. 这是一个非标准的事情,

我很感激您对此有任何建议。

I appreciate any advice on this.

尝试将 style 元素添加到而不是正文

Try adding the style element to the head rather than the body.

9),Firefox,Opera和Chrome:

This was tested in IE (7-9), Firefox, Opera and Chrome:

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

style.type = 'text/css';
if (style.styleSheet){
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}

head.appendChild(style);