class-util.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { isIE9 } from 'web/util/index'
  2. import { namespaceMap } from './node-ops'
  3. const svgNS = namespaceMap.svg
  4. /**
  5. * In IE9, setAttribute('class') will result in empty class
  6. * if the element also has the :class attribute; However in
  7. * PhantomJS, setting `className` does not work on SVG elements...
  8. * So we have to do a conditional check here.
  9. *
  10. * @param {Element} el
  11. * @param {String} cls
  12. */
  13. export function setClass (el, cls) {
  14. /* istanbul ignore else */
  15. if (!isIE9 || el.namespaceURI === svgNS) {
  16. el.setAttribute('class', cls)
  17. } else {
  18. el.className = cls
  19. }
  20. }
  21. /**
  22. * Add class with compatibility for IE & SVG
  23. *
  24. * @param {Element} el
  25. * @param {String} cls
  26. */
  27. export function addClass (el, cls) {
  28. if (el.classList) {
  29. if (cls.indexOf(' ') > -1) {
  30. cls.split(/\s+/).forEach(c => el.classList.add(c))
  31. } else {
  32. el.classList.add(cls)
  33. }
  34. } else {
  35. let cur = ' ' + getClass(el) + ' '
  36. if (cur.indexOf(' ' + cls + ' ') < 0) {
  37. setClass(el, (cur + cls).trim())
  38. }
  39. }
  40. }
  41. /**
  42. * Remove class with compatibility for IE & SVG
  43. *
  44. * @param {Element} el
  45. * @param {String} cls
  46. */
  47. export function removeClass (el, cls) {
  48. if (el.classList) {
  49. if (cls.indexOf(' ') > -1) {
  50. cls.split(/\s+/).forEach(c => el.classList.remove(c))
  51. } else {
  52. el.classList.remove(cls)
  53. }
  54. } else {
  55. let cur = ' ' + getClass(el) + ' '
  56. let tar = ' ' + cls + ' '
  57. while (cur.indexOf(tar) >= 0) {
  58. cur = cur.replace(tar, ' ')
  59. }
  60. setClass(el, cur.trim())
  61. }
  62. if (!el.className) {
  63. el.removeAttribute('class')
  64. }
  65. }
  66. /**
  67. * For IE9 compat: when both class and :class are present
  68. * getAttribute('class') returns wrong value... but className
  69. * on SVG elements returns an object.
  70. *
  71. * @param {Element} el
  72. * @return {String}
  73. */
  74. function getClass (el) {
  75. var classname = el.className
  76. if (typeof classname === 'object') {
  77. classname = classname.baseVal || ''
  78. }
  79. return classname
  80. }