原生js实现addClass, removeClass 方法

addClass

export function addClass(elem, className) {
  if (!className) return;

  const els = Array.isArray(elem) ? elem : [elem];

  els.forEach((el) => {
    if (el.classList) {
      el.classList.add(className.split(' '));
    } else {
      el.className += ` ${className}`;
    }
  });
}

removeClass

export function removeClass(elem, className) {
  if (!className) return;

  const els = Array.isArray(elem) ? elem : [elem];
  els.forEach((el) => {
    if (el.classList) {
      el.classList.remove(className.split(' '));
    } else {
      el.className = el.className.replace(new RegExp(`(^|\\b)${className.split(' ').join('|')}(\\b|$)`, 'gi'), ' ');
    }
  });
}

你可能感兴趣的:(原生js实现addClass, removeClass 方法)