Domanda

This is a simplified version of how to dynamically change a selector rule:

http://jsfiddle.net/vsync/SaQy6/

For a giver inline style:

<style type='text/css' id='myStyle'>
    ul > li{}
</style>

trying to change the selector

var styleTag = document.querySelector('#myStyle');
// the style sheet in the style tag
var sheet = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet,
    // the first rule in the style sheet
    rules = sheet.cssRules ? sheet.cssRules : sheet.rules;

rules[0].selectorText = 'ul > li:nth-child(2)';
rules[0].style.cssText = 'background:red';

Nor selectorText or cssText work to set the selector dynbamically.

Then I read on MDN that selectorText is readOnly, and I am lost as to how should I actually change the selector without having to remove the whole style element and creating a new one. There is the option of removing the rule completely and inserting a new rule, but it's very non-standard. Any ideas?

È stato utile?

Soluzione

Demo - http://jsfiddle.net/vsync/SaQy6/6/

cross-browser way:

var styleTag = document.querySelector('#myStyle');
// the style sheet in the style tag
var sheet = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet,
    rules = sheet.cssRules ? sheet.cssRules : sheet.rules;

if( sheet.cssRules ){
    sheet.deleteRule(0); // deletes a rule at index 0
    sheet.insertRule("ul > li:nth-child(2n){background:red}", 0);
}
else{
    sheet.removeRule(0); // deletes a rule at index 0
    sheet.addRule("ul > li:nth-child(2n)", 'background:red', 0);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top