javascript – 将CSS字符串注入新文档样式表

我正在动态创建一个大型样式表作为字符串,并希望将其注入iframe.最初我接近它是这样的:

var css = '.newstyle { margin: 20px; } .newstyle2 { margin: 20px; }';
$('iframe').contents().find('head').append('<style type="text/css">'+css+'</style>');

不幸的是,IE7不喜欢这种方法.我不确定如何处理这种注射.是否有一个跨浏览器的解决方案,使我能够从字符串中注入大量的CSS?

最佳答案 您可以将document.stylesheets用于此目的.它使您可以访问页面中的样式表.

查看这篇文章:http://kentbrewster.com/creating-dynamic-stylesheets/ – 它有点旧,而不是以jQuery为中心,但我相信你可以根据自己的需要进行调整.几年前我使用过这种技术,我相信在调整一下之后它在所有浏览器中都运行良好.

这里有关于stylesheets属性的更多信息:

> http://www.quirksmode.org/dom/changess.html
> https://developer.mozilla.org/en/DOM/document.styleSheets

点赞