81151d76acb6fff6e333b1fad59719944388d0c76a14dfad15e5b2f206000bb856c03ecaf60b96885d9de616a07c4c0c25cd8dec6fb5120270836994a8ced9 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* @flow */
  2. const whitespaceRE = /\s+/
  3. /**
  4. * Add class with compatibility for SVG since classList is not supported on
  5. * SVG elements in IE
  6. */
  7. export function addClass (el: HTMLElement, cls: ?string) {
  8. /* istanbul ignore if */
  9. if (!cls || !(cls = cls.trim())) {
  10. return
  11. }
  12. /* istanbul ignore else */
  13. if (el.classList) {
  14. if (cls.indexOf(' ') > -1) {
  15. cls.split(whitespaceRE).forEach(c => el.classList.add(c))
  16. } else {
  17. el.classList.add(cls)
  18. }
  19. } else {
  20. const cur = ` ${el.getAttribute('class') || ''} `
  21. if (cur.indexOf(' ' + cls + ' ') < 0) {
  22. el.setAttribute('class', (cur + cls).trim())
  23. }
  24. }
  25. }
  26. /**
  27. * Remove class with compatibility for SVG since classList is not supported on
  28. * SVG elements in IE
  29. */
  30. export function removeClass (el: HTMLElement, cls: ?string) {
  31. /* istanbul ignore if */
  32. if (!cls || !(cls = cls.trim())) {
  33. return
  34. }
  35. /* istanbul ignore else */
  36. if (el.classList) {
  37. if (cls.indexOf(' ') > -1) {
  38. cls.split(whitespaceRE).forEach(c => el.classList.remove(c))
  39. } else {
  40. el.classList.remove(cls)
  41. }
  42. if (!el.classList.length) {
  43. el.removeAttribute('class')
  44. }
  45. } else {
  46. let cur = ` ${el.getAttribute('class') || ''} `
  47. const tar = ' ' + cls + ' '
  48. while (cur.indexOf(tar) >= 0) {
  49. cur = cur.replace(tar, ' ')
  50. }
  51. cur = cur.trim()
  52. if (cur) {
  53. el.setAttribute('class', cur)
  54. } else {
  55. el.removeAttribute('class')
  56. }
  57. }
  58. }