Add a new class into the css style with javascript
how can i insert a new class into the current css?
var myStyle = $("head > style:eq(2)");
if( document.styleSheets[2开发者_如何学Python].cssRules ) {
myStyle.insertRule('#test { display:block; }', 0);
} else {
if ( document.styleSheets[2].rules ) {
myStyle.addRule('#test', 'display:block;');
}
}
dd
You appear to be switching between a styleSheet object and the result of a framework's selector function (possibly jQuery). Stick with document.styleSheets for the whole thing:
var myStyle = document.styleSheets[2];
if( myStyle.cssRules ) {
myStyle.insertRule('#test { display:block; }', 0);
} else if ( myStyle.rules ) {
myStyle.addRule('#test', 'display:block;');
}
nb: I did away with the redundant if block, switching to an else if instead. You could do away with the else if condition and just leave it as else, if you wanted.
精彩评论