/ Published in: JavaScript
Support: Fx2, Opera9, IE6 CSS.add() can add style rules by the method of like GM_addStyle(). This can add Style string at high speed, because it doesn't use a handmade parser.
Expand |
Embed | Plain Text
/*----------------------------------------------------------------------------- * CSS writer * Example Source CSS.add( 'body { background: #eee; color: #333; }', '#id .class { display: block; width: 100%; }', 'a:link, a:visited { color: #00f; }', 'a:active, a:hover { color: #f00; }' ); var value1 = CSS.get('#wrapper', 'width'); var value2 = CSS.get($('id'), 'color', 'hover'); *-------------------------------------------------------------------------- */ var CSS = { _add: function (selector, property) { var css = document.styleSheets[0]; if (css.addRule) css.addRule(selector, '{' + property + '}'); else if (css.insertRule) css.insertRule(selector + '{' + property + '}', css.cssRules.length); }, add: function () { $A(arguments).join('').split('}').remove('').forEach(function (css) { var tmp = css.split('{'); CSS._add(tmp[0], tmp[1]); }); }, get: function (selector, property, pseudo) { if (isString(selector)) { var sheets = document.styleSheets; (sheets[0].rule) && (selector = selector.replace(/\*/g, '')); for (var i = 0, len = sheets.length; i < len; ++i) { var sheet = sheets[i].rule || sheets[i].cssRules; for (var j = 0, l = sheet.length; j < len; ++j) { var css = sheet[i]; if (css.selectorText.toLowerCase() == selector.toLowerCase()) return css.style[property]; } } return null; } else return ( (selector.currentStyle) ? selector.currentStyle[property.toCamelize()] : (document.defaultView.getComputedStyle) ? document.defaultView.getComputedStyle(selector, pseudo).getPropertyValue(property.toSelector()) : '' ); } } /* * Extend */ function $A(v) { if (!v) return []; if (isArray(v)) return v; if (v.toArray) return v.toArray(); else { var len = v.length; var res = new Array(len); for (var i = 0; i < len; ++i) res[i] = v[i]; return res; } } Array.prototype.filter || (Array.prototype.filter = function (callback, thisobj) { var res = []; for (var i = 0, len = this.length; i < len; ++i) callback.call(thisobj, this[i], i, this) && res.push(this[i]); return res; }); Array.prototype.remove = function (rule) { return this.filter(function (val) { return (val != rule); }); } Array.prototype.forEach || (Array.prototype.forEach = function (callback, thisobj) { for (var i = 0, len = this.length; i < len; ++i) callback.call(thisobj, this[i], i, this); }); String.prototype.toCamelize = function () { return this.replace(/\-(.)/g, function (x, y) { return y.toUpperCase(); }); } String.prototype.toSelector = function () { return this.replace(/([A-Z])/g, '-$1').toLowerCase(); }
You need to login to post a comment.
