如何创建< style>用Javascript标记?

问题描述:

我正在寻找一种方法将< style> 标记插入带有JavaScript的HTML页面。

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。 IE前面的< br> 也有点难看。

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. 更好

  1. Is nicer

适用于Chrome?

或许


  1. 这是我应该避免的非标准事项

  1. This is a non-standard thing I should avoid

三种工作浏览器都很棒,无论如何都使用Chrome?

Three working browsers are great and who uses Chrome anyway?


尝试将样式元素添加到 head 而不是正文

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

这是在IE(7-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){
  // This is required for IE8 and below.
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}

head.appendChild(style);