简体   繁体   中英

Programatically create new CSS rules in a stylesheet

For creating new CSS rules in a stylesheet, as of now, I only know .insertRule() (excluding the non-standard ways).

Are there any other ways of creating more CSS rules? Something, for example:
Warning: this is not standard, it is just an example to display the intent

var rule = new CSSStyleRule();
rule.selectorText = '.selector';
rule.style.display = 'block';
rule.style.color = 'red';
ruleSet.append(rule);

Anything like or somewhat like the above works as an answer. Instead of new , it may be document.createCssRule() or stylesheet.createCssRule() ... I just this it would be useful for a piece of software I'm developing which left me if there's a programatically way of modifying values in such interface where to add new stuff is not restricted to a parsed string.

Do not worry about IE9 and below when answering, please.

Note: (to unclose) This is not about how to find and modify current CSS rules, this is about making new ones without using the text parser which is what .insertRule() is without building a complete CSS string like .insertRule() requires.

You could append a new style element to your head and just append rules to it:

function addStyle(newRules){
    if(document.getElementById("jsAddedRules")){
        document.getElementById("jsAddedRules").innerHTML+=newRules;
    }else{
        var style=document.createElement("style");
        style.setAttribure("id","jsAddedRules");
        style.innerHTML=newRules;
        document.getElementsByTagName("head")[0].appendChild(style);
    }
}

And then just call your function when you want to add rules:

addStyle(
    ".selector{\
        display:block;\
        color:red;\
    }"
);

You can add an empty rule, get it, and modify it:

 function appendRule(sheet) { var len = sheet.cssRules.length; sheet.insertRule('*{}', len); return sheet.cssRules[len]; } var rule = appendRule(document.styleSheets[0]); rule.selectorText = '.selector'; rule.style.display = 'block'; rule.style.color = 'red'; 
 <span class="selector">I should become red.</span> <span>I should be at the next line and not become red.</span> 

However, modifying selectorText does not seem to work on Firefox.

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