Created
March 23, 2012 18:35
-
-
Save mseeley/2173606 to your computer and use it in GitHub Desktop.
Easily alter CSS rules via JS
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
// Allows programmatic altering of CSS rules. Turn this class into a flyweight by enabling modification of the underlying rule property. | |
function CssRule (selector, stylesheet) { | |
var rules = stylesheet.rules, | |
len = rules.length, | |
i = 0, | |
rule = null; | |
for (i; i < len; i++) { | |
rule = rules[i]; | |
if (rule.selectorText === selector) { | |
this.rule = rule; | |
break; | |
} | |
} | |
} | |
CssRule.prototype = { | |
rule: null, | |
set: function (key, value) { | |
this.rule.style[key] = value; | |
return value; | |
}, | |
get: function (key) { | |
return this.rule.style[key]; | |
}, | |
destroy: function () { | |
delete this.rule; | |
} | |
}; | |
/* | |
Example: | |
<style type='text/css'> | |
.anim { | |
-webkit-transition-duration:300ms; | |
} | |
</style> | |
<script> | |
var anim = new CssRule('.anim', document.stylesheets[0]); | |
anim.get('webkitTransitionDuration'); // '300ms' | |
anim.set('webkitTransitionDuration', '100ms'); // '100ms' | |
</script> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment