How to create a lt;stylegt; tag with Javascript?(如何创建lt;风格gt;用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
更好
适用于 Chrome?
Works with Chrome?
或许
这是我应该避免的非标准事情
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));
}
这篇关于如何创建<风格>用Javascript标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何创建<风格>用Javascript标记?


基础教程推荐
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 响应更改 div 大小保持纵横比 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01