Create dynamic inline stylesheet
What is the best way of creating dynamic style tags using js and/or jQuery?
I tried this:
var style= jQuery('<style>').text('.test{}');
This works in FF but pops an error in IE7 "Unexpected call to method or property access."
开发者_运维技巧var style = document.createElement('style');
style.innerHTML='.test{}';
Gives the same error. It doesn't matter if I use innerHTML
or innerText
. The strange thing is that it shows an error before appending the style tag.
I suspect that cssText
has something to do with it, but I'm not sure how.
Adding text to a stylesheet that will be rendered correctly needs a different syntax in IE than other browsers. You may be able to use some of this with jquery
document.addStyle= function(str, hoo, med){
var el= document.createElement('style');
el.type= "text/css";
el.media= med || 'screen';
if(hoo) el.title= hoo;
if(el.styleSheet) el.styleSheet.cssText= str;//IE only
else el.appendChild(document.createTextNode(str));
return document.getElementsByTagName('head')[0].appendChild(el);
}
This method of generating css rules dynamically will be flawed even if it worked. IE will simply ignore <style>
elements after more then 30 have been inserted (see http://support.microsoft.com/kb/262161).
You can use the jquery.rule plugin for the purpose of manipulating css rules through javascript.
I would look into Javascript's document.styleSheets
, and the addRule()
method.
(Disclaimer: I've never actually used this myself)
精彩评论