简体   繁体   中英

Injecting CSS String as New Document Stylesheet

I am dynamically creating a large stylesheet as a string and desiring to injecting it into an iframe. Initially I approached it like this:

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

Unfortunately, IE7 does not like this method. I'm not sure how else to approach this injection. Is there a cross-browser solution that will enable me to inject a mass of CSS from a string?

You could use document.stylesheets for this purpose. It gives you access to the style sheets within a page.

Check this article: http://kentbrewster.com/creating-dynamic-stylesheets/ — It's a bit older and not jQuery–centric, but I'm sure you can adjust it to your needs. I've used this technique a few years back and I believe it worked fine in all browsers after tweaking a bit.

Here's a bit more information on the stylesheets property:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM