gpt4 book ai didi

javascript - 创建和填充 <style> 元素

转载 作者:行者123 更新时间:2023-11-27 22:41:59 26 4
gpt4 key购买 nike

Firefox 和 Chrome 让我创建一个 <style>元素并填充它,全部来自 JavaScript。我可以发誓,过去我曾在不同的情况下在 IE(如 IE6)中这样做过。但是现在我根本无法让 IE(7 或 8;还没有尝试过 9)让我设置它。

我记得有一个“cssText”属性,但现在(神秘地减少了;有人知道 MSDN 文档站点发生了什么吗?)MSDN 文档只显示为样式表 API 的一部分,而不是作为样式表 API 的一部分一个 DOM 元素。

那么:是否有可能创建并填充 <style> Internet Explorer 中的元素?

Here是一个简单的 jsfiddle 示例,具有以下 jQuery 代码:

$('head').append($('<style/>', { html: 'div { color: red; }' }));

在 Firefox、Chrome 和 Opera 中运行良好。 (我想我应该尝试一下 Android 和 iOS。)

编辑 — 是的,我试过设置“文本”而不​​是“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 - 创建和填充 &lt;style&gt; 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10353560/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com