如何创建<风格>用Javascript标记?

2022-01-30 00:00:00 javascript html css

我正在寻找一种使用 JavaScript 将 <style> 标记插入 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. 更好

适用于 Chrome?

Works with Chrome?

或许

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

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

三个工作浏览器都很棒,还有谁在使用 Chrome?

Three working browsers are great and who uses Chrome anyway?

推荐答案

尝试将 style 元素添加到 head 而不是 body.

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');

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));
}

相关文章