如何创建< style>标签与Javascript [英] How to create a <style> tag with Javascript

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

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

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