class-util.js 1.2 KB

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