如何创建<样式>用 Javascript 标记? [英] How to create a <style> tag with Javascript?

查看:22
本文介绍了如何创建<样式>用 Javascript 标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用 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));
}

这篇关于如何创建&lt;样式&gt;用 Javascript 标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆