Native js implementation elements class names sentenced save, add and remove

1, addClass: add style to the specified dom elements.

2, removeClass: delete the specified dom element of style.

3, toggleClass: if exists (does not exist), delete (add) a style.

4, hasClass: to determine whether there is style.

 

function hasClass(obj, cls) {
    return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
 
function addClass(obj, cls) {
    if (!this.hasClass(obj, cls)) {
        obj.className += " " + cls;
    }
}
 
function removeClass(obj, cls) {
    if (hasClass(obj, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        obj.className = obj.className.replace(reg, ' ');
    }
}
 
function toggleClass(obj,cls){
    if(hasClass(obj,cls)){
        removeClass(obj, cls);
    } else {
        addClass(obj, cls);
    }
}

 

Guess you like

Origin www.cnblogs.com/gopark/p/12040131.html