js 动态添加class封装(es6语法)

export function hasClass(el, className) {
  let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
  return reg.test(el.className)
}

export function addClass(el, className) {
  if (hasClass(el, className)) {
    return
  }

  let newClass = el.className.split(' ')
  newClass.push(className)
  el.className = newClass.join(' ')
}

addClass(元素, 'item-类名')

转载于:https://www.cnblogs.com/Byme/p/9558188.html

你可能感兴趣的:(js 动态添加class封装(es6语法))