1. 程式人生 > >原生javascript實現 hasClass addClass removeClass

原生javascript實現 hasClass addClass removeClass

javascrip replace name regex rep || classname ddc exp

function hasClass(elem, cls) {
  cls = cls || ‘‘;
  if (cls.replace(/\s/g, ‘‘).length == 0) return false; 
  return new RegExp(‘ ‘ + cls + ‘ ‘).test(‘ ‘ + elem.className + ‘ ‘);
}
 
function addClass(ele, cls) {
  if (!hasClass(elem, cls)) {
    ele.className = ele.className == ‘‘ ? cls : ele.className + ‘ ‘ + cls;
  }
}
 
function removeClass(ele, cls) {
  if (hasClass(elem, cls)) {
    var newClass = ‘ ‘ + elem.className.replace(/[\t\r\n]/g, ‘‘) + ‘ ‘;
    while (newClass.indexOf(‘ ‘ + cls + ‘ ‘) >= 0) {
      newClass = newClass.replace(‘ ‘ + cls + ‘ ‘, ‘ ‘);
    }
    elem.className = newClass.replace(/^\s+|\s+$/g, ‘‘);
  }
}

原生javascript實現 hasClass addClass removeClass