CSSStyleSheet.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //.CommonJS
  2. var CSSOM = {
  3. StyleSheet: require("./StyleSheet").StyleSheet,
  4. CSSStyleRule: require("./CSSStyleRule").CSSStyleRule
  5. };
  6. ///CommonJS
  7. /**
  8. * @constructor
  9. * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet
  10. */
  11. CSSOM.CSSStyleSheet = function CSSStyleSheet() {
  12. CSSOM.StyleSheet.call(this);
  13. this.cssRules = [];
  14. };
  15. CSSOM.CSSStyleSheet.prototype = new CSSOM.StyleSheet();
  16. CSSOM.CSSStyleSheet.prototype.constructor = CSSOM.CSSStyleSheet;
  17. /**
  18. * Used to insert a new rule into the style sheet. The new rule now becomes part of the cascade.
  19. *
  20. * sheet = new Sheet("body {margin: 0}")
  21. * sheet.toString()
  22. * -> "body{margin:0;}"
  23. * sheet.insertRule("img {border: none}", 0)
  24. * -> 0
  25. * sheet.toString()
  26. * -> "img{border:none;}body{margin:0;}"
  27. *
  28. * @param {string} rule
  29. * @param {number} index
  30. * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-insertRule
  31. * @return {number} The index within the style sheet's rule collection of the newly inserted rule.
  32. */
  33. CSSOM.CSSStyleSheet.prototype.insertRule = function(rule, index) {
  34. if (index < 0 || index > this.cssRules.length) {
  35. throw new RangeError("INDEX_SIZE_ERR");
  36. }
  37. var cssRule = CSSOM.parse(rule).cssRules[0];
  38. cssRule.parentStyleSheet = this;
  39. this.cssRules.splice(index, 0, cssRule);
  40. return index;
  41. };
  42. /**
  43. * Used to delete a rule from the style sheet.
  44. *
  45. * sheet = new Sheet("img{border:none} body{margin:0}")
  46. * sheet.toString()
  47. * -> "img{border:none;}body{margin:0;}"
  48. * sheet.deleteRule(0)
  49. * sheet.toString()
  50. * -> "body{margin:0;}"
  51. *
  52. * @param {number} index within the style sheet's rule list of the rule to remove.
  53. * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-deleteRule
  54. */
  55. CSSOM.CSSStyleSheet.prototype.deleteRule = function(index) {
  56. if (index < 0 || index >= this.cssRules.length) {
  57. throw new RangeError("INDEX_SIZE_ERR");
  58. }
  59. this.cssRules.splice(index, 1);
  60. };
  61. /**
  62. * NON-STANDARD
  63. * @return {string} serialize stylesheet
  64. */
  65. CSSOM.CSSStyleSheet.prototype.toString = function() {
  66. var result = "";
  67. var rules = this.cssRules;
  68. for (var i=0; i<rules.length; i++) {
  69. result += rules[i].cssText + "\n";
  70. }
  71. return result;
  72. };
  73. //.CommonJS
  74. exports.CSSStyleSheet = CSSOM.CSSStyleSheet;
  75. CSSOM.parse = require('./parse').parse; // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleSheet.js
  76. ///CommonJS