Created
February 21, 2009 16:00
-
-
Save magmoro/68080 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var StyleSheet=new Class({ | |
initialize: function(){ | |
this.createSheet(); | |
this.rules={}; | |
this.styles={}; | |
this.index=[]; | |
}, | |
createSheet: function(){ | |
var style = new Element('style').inject(document.head); | |
this.sheet=style.styleSheet||style.sheet; | |
}, | |
addRule: function(selector, styles){ | |
selector=selector.trim(); | |
if(selector.contains(',')){ | |
var selectors=selector.split(','); | |
selectors.each(function(selector){ | |
this.addRule(selector, styles); | |
}, this); | |
return this; | |
} | |
var styles=$type(styles)=='string' ? styles : this.stylesToString(styles); | |
var sheet=this.sheet; | |
if(sheet.addRule){ | |
sheet.addRule(selector, styles); | |
}else{ | |
sheet.insertRule(selector+'{'+styles+'}', sheet.cssRules.length); | |
} | |
var rules=this.getRules(); | |
this.rules[selector]=rules.getLast(); | |
this.styles[selector]=styles; | |
this.index.push(selector); | |
return this; | |
}, | |
addRules: function(rules){ | |
for(selector in rules) | |
this.addRule(selector, rules[selector]); | |
return this; | |
}, | |
stylesToString: function(styles){ | |
var string=''; | |
for(p in styles) | |
string+=p.hyphenate()+':'+styles[p]+';\n'; | |
return string; | |
}, | |
removeRule: function(index){ | |
var sheet=this.sheet; | |
if($type(index)=='string'){ | |
var selector=index.trim(); | |
if(selector.contains(',')){ | |
var selectors=selector.split(','); | |
selectors.each(function(selector){ | |
this.removeRule(selector); | |
}, this); | |
return this; | |
} | |
var index=this.getRules().indexOf(this.getRule(selector)); | |
if(index<0) return this; | |
} | |
sheet.removeRule ? sheet.removeRule(index) : sheet.deleteRule(index); | |
var selector=this.index[index]; | |
this.index.erase(selector); | |
delete this.rules[selector]; | |
delete this.styles[selector]; | |
return this; | |
}, | |
getRule: function(selector){ | |
return $type(selector)=='string' ? this.rules[selector] : this.getRules()[selector]; | |
}, | |
getRules: function(){ | |
return $A(this.sheet.cssRules||this.sheet.rules); | |
} | |
}); | |
StyleSheet.implement({ | |
debug: function(){ | |
var code=''; | |
for(selector in this.styles){ | |
code+=selector+'{\n'+this.styles[selector]+'}\n'; | |
} | |
return code; | |
} | |
}); | |
var newSheet=new StyleSheet(); | |
newSheet.addRule('html, body', { | |
border: 'solid 10px black' | |
}).addRule('div',{ | |
color: '#a2ec9f' | |
}); | |
newSheet.removeRule('body'); | |
alert(newSheet.debug()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment