Firefox 和 Chrome 让我创建一个 <style>
元素并填充它,全部来自 JavaScript。我可以发誓,过去我曾在 IE(例如 IE6)中的不同情况下这样做过。但现在我根本无法让 IE(7 或 8;还没有尝试过 9)让我进行设置。
我记得有一个“cssText”属性,但现在在(神秘地减少了;有人知道 MSDN 文档网站发生了什么吗?)MSDN 文档仅显示为样式表 API 的一部分,而不是作为DOM 元素的东西。
那么:是否有可能创建并填充 <style>
Internet Explorer 中的元素?
Here是一个简单的 jsfiddle 示例,具有以下 jQuery 代码:
$('head').append($('<style/>', { html: 'div { color: red; }' }));
在 Firefox、Chrome 和 Opera 中运行良好。 (我想我应该尝试 Android 和 iOS。)
编辑 - 是的,我尝试设置“text”而不是“html”,但没有帮助。尝试在没有 jQuery 的情况下设置“innerText”也不起作用。
最佳答案
这是我之前的做法。我几乎直接从我的一些旧代码中复制了这个,但如果我没记错的话, styleSheet
属性仅由 IE 使用,正如您所提到的,那就是您需要使用 cssText
:
var styleElem = document.createElement("style");
styleElem.type = "text/css";
styleRules = document.createTextNode(".someClass { color: red; }");
if(styleElem.styleSheet) {
styleElem.styleSheet.cssText = styleRules.nodeValue;
}
else {
styleElem.appendChild(styleRules);
}
document.getElementsByTagName("head")[0].appendChild(styleElem);
这是一个working example (在最新的 Chrome 和 IE6 中测试)。
关于javascript - 创建并填充 <style> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10353560/