styled.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. define(function(require, exports, module) {
  2. // polyfill for ie
  3. var ClassList = require('../core/class').createClass('ClassList', {
  4. constructor: function(node) {
  5. this._node = node;
  6. this._list = node.className.toString().split(' ');
  7. },
  8. _update: function() {
  9. this._node.className = this._list.join(' ');
  10. },
  11. add: function(name) {
  12. this._list.push(name);
  13. this._update();
  14. },
  15. remove: function(name) {
  16. var index = this._list.indexOf(name);
  17. if (~index) {
  18. this._list.splice(index, 1);
  19. }
  20. this._update();
  21. },
  22. contains: function(name) {
  23. return !!~this._list.indexOf(name);
  24. }
  25. });
  26. function getClassList(node) {
  27. if (!node.classList) {
  28. node.classList = new ClassList(node);
  29. }
  30. return node.classList;
  31. }
  32. return require('../core/class').createClass('Styled', {
  33. addClass: function(name) {
  34. getClassList(this.node).add(name);
  35. return this;
  36. },
  37. removeClass: function(name) {
  38. getClassList(this.node).remove(name);
  39. return this;
  40. },
  41. hasClass: function(name) {
  42. return getClassList(this.node).contains(name);
  43. },
  44. setStyle: function(styles) {
  45. if (arguments.length == 2) {
  46. this.node.style[arguments[0]] = arguments[1];
  47. return this;
  48. }
  49. for (var name in styles) {
  50. if (styles.hasOwnProperty(name)) {
  51. this.node.style[name] = styles[name];
  52. }
  53. }
  54. return this;
  55. }
  56. });
  57. });