博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何创建一个<style> tag with Javascript?
阅读量:3577 次
发布时间:2019-05-20

本文共 3741 字,大约阅读时间需要 12 分钟。

本文翻译自:

I'm looking for a way to insert a <style> tag into an HTML page with JavaScript. 我正在寻找一种使用JavaScript将<style>标记插入HTML页面的方法。

The best way I found so far: 到目前为止,我发现的最好方法是:

var divNode = document.createElement("div");divNode.innerHTML = "
";document.body.appendChild(divNode);

This works in Firefox, Opera and Internet Explorer but not in Google Chrome. 这在Firefox,Opera和Internet Explorer中有效,但在Google Chrome中不起作用。 Also it's a bit ugly with the <br> in front for IE. IE前面的<br>也有点难看。

Does anyone know of a way to create a <style> tag that 有谁知道创建<style>标签的方法吗?

  1. Is nicer 更好

  2. Works with Chrome? 使用Chrome吗?

Or maybe 或许

  1. This is a non-standard thing I should avoid 这是我应该避免的非标准事情

  2. Three working browsers are great and who uses Chrome anyway? 三种运行良好的浏览器都很棒,到底谁在使用Chrome?


#1楼

参考:


#2楼

Here is a variant for dynamically adding a class 这是用于动态添加类的变体

function setClassStyle(class_name, css) {  var style_sheet = document.createElement('style');  if (style_sheet) {    style_sheet.setAttribute('type', 'text/css');    var cstr = '.' + class_name + ' {' + css + '}';    var rules = document.createTextNode(cstr);    if(style_sheet.styleSheet){// IE      style_sheet.styleSheet.cssText = rules.nodeValue;    } else {      style_sheet.appendChild(rules);    }    var head = document.getElementsByTagName('head')[0];    if (head) {      head.appendChild(style_sheet);    }  }}

#3楼

All good, but for styleNode.cssText to work in IE6 with node created by javascipt, you need to append the node to the document before you set the cssText; 一切都很好,但是要使styleNode.cssText在IE6中与javascipt创建的节点一起工作,需要在设置cssText之前将节点附加到文档中;

further info @ 更多信息@


#4楼

Oftentimes there's a need to override existing rules, so appending new styles to the HEAD doesn't work in every case. 通常,需要覆盖现有规则,因此在每种情况下都无法向HEAD附加新样式。

I came up with this simple function that summarizes all not valid "append to the BODY" approaches and is just more convenient to use and debug (IE8+). 我想出了这个简单的函数,它总结了所有无效的 “附加到BODY”方法,并且使用和调试更加方便(IE8 +)。

window.injectCSS = (function(doc){    // wrapper for all injected styles and temp el to create them    var wrap = doc.createElement('div');    var temp = doc.createElement('div');    // rules like "a {color: red}" etc.    return function (cssRules) {        // append wrapper to the body on the first call        if (!wrap.id) {            wrap.id = 'injected-css';            wrap.style.display = 'none';            doc.body.appendChild(wrap);        }        // 
for IE: http://goo.gl/vLY4x7 temp.innerHTML = '
'; wrap.appendChild( temp.children[1] ); };})(document);

Demo: , 演示: ,


#5楼

This object variable will append style tag to the head tag with type attribute and one simple transition rule inside that matches every single id/class/element. 该对象变量会将style标签附加到具有type属性和一个简单转换规则的head标签上,该规则与每个id / class / element匹配。 Feel free to modify content property and inject as many rules as you need. 可以随意修改content属性并根据需要注入任意数量的规则。 Just make sure that css rules inside content remain in one line (or 'escape' each new line, if You prefer so). 只要确保内容中的CSS规则保持一行即可(或者,如果愿意,可以“转义”每一行)。

var script = {  type: 'text/css', style: document.createElement('style'),   content: "* { transition: all 220ms cubic-bezier(0.390, 0.575, 0.565, 1.000); }",  append: function() {    this.style.type = this.type;    this.style.appendChild(document.createTextNode(this.content));    document.head.appendChild(this.style);}}; script.append();

#6楼

<style> tags should be places within the <head> element, and each added tag should be added to the bottom of the <head> tag. <style>标签应放在<head>元素内,每个添加的标签应添加到<head>标签的底部。

Using to inject a style tag into the document : 使用将样式标签注入文档的 :

Native DOM: 本机DOM:

document.head.insertAdjacentHTML("beforeend", ``)


jQuery : jQuery的

$('

转载地址:http://rwmgj.baihongyu.com/

你可能感兴趣的文章
实现自己的权限管理系统(十):角色模块
查看>>
实现自己的权限管理系统(十二):权限操作记录
查看>>
实现自己的权限管理系统(十三):redis做缓存
查看>>
实现自己的权限管理系统(十四):工具类
查看>>
JavaWeb面经(二):2019.9.16 Synchronized关键字底层原理及作用
查看>>
牛客的AI模拟面试(1)
查看>>
深入浅出MyBatis:MyBatis解析和运行原理
查看>>
Mybatis与Ibatis
查看>>
字节码文件(Class文件)
查看>>
java中的IO流(一)----概述
查看>>
StringBuilder
查看>>
集合,Collection
查看>>
泛型详解
查看>>
泛型实现斗地主
查看>>
List集合
查看>>
ArrayList集合,LinkedList集合,Vector集合
查看>>
HashSet集合
查看>>
并发与并行,线程与进程
查看>>
方法引用,通过对象名引用成员变量
查看>>
常用工具类 Math:数学计算 Random:生成伪随机数 SecureRandom:生成安全的随机数 2020-2-13
查看>>