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标记?
基础教程推荐
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
