添加、删除类名

addClass,removeClass,hasClass-用于处理 DOM 元素类的三个重要函数


浏览器支持的操作元素的class属性的便捷方法有:classList.add()classList.remove()classList.contains()。 不过IE浏览器支持度还不够高。 因此如果要兼容IE,我们需要使用与jQuery方法$.addClass()$.removeClass()$.hasClass()相对应的简短辅助函数:


function hasClass(el, className) {
    return el.classList ? el.classList.contains(className) : new RegExp('\b'+ className+'\b').test(el.className);
}

function addClass(el, className) {
    if (el.classList) el.classList.add(className);
    else if (!hasClass(el, className)) el.className += ' ' + className;
}

function removeClass(el, className) {
    if (el.classList) el.classList.remove(className);
    else el.className = el.className.replace(new RegExp('\b'+ className+'\b', 'g'), '');
}
      

使用示例如下:


var el = document.querySelector('div');
if (!hasClass(el, 'foo')) addClass(el, 'foo');
      

如果要同时对许多个类名进行操作,则可以采用稍微不同且性能更好的方法,代码如下:


var hasClass, addClass, removeClass;

if ('classList' in document.documentElement) {
    hasClass = function (el, className) { return el.classList.contains(className); };
    addClass = function (el, className) { el.classList.add(className); };
    removeClass = function (el, className) { el.classList.remove(className); };
} else {
    hasClass = function (el, className) {
        return new RegExp('\b'+ className+'\b').test(el.className);
    };
    addClass = function (el, className) {
        if (!hasClass(el, className)) { el.className += ' ' + className; }
    };
    removeClass = function (el, className) {
        el.className = el.className.replace(new RegExp('\b'+ className+'\b', 'g'), '');
    };
}
      

如果需要,你可以创建一个toggleClass方法去方便的切换类名


var hasClass, addClass, removeClass, toggleClass;

if ('classList' in document.documentElement) {
    hasClass = function (el, className) { return el.classList.contains(className); };
    addClass = function (el, className) { el.classList.add(className); };
    removeClass = function (el, className) { el.classList.remove(className); };
} else {
    hasClass = function (el, className) {
        return new RegExp('\b'+ className+'\b').test(el.className);
    };
    addClass = function (el, className) {
        if (!hasClass(el, className)) { el.className += ' ' + className; }
    };
    removeClass = function (el, className) {
        el.className = el.className.replace(new RegExp('\b'+ className+'\b', 'g'), '');
    };
}

toggleClass = function (el, className) {
  if (hasCLass(el, className)) {
    removeClass(el, className)
  } else {
    addClass(el, className)
  }
}