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

查看:108
本文介绍了如何创建< 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);

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

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