原生js 实现jquery addClass,removeClass

代码如下:

 

function hasClass(obj, cls) {
let reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
return obj.className.match(reg);
}

function addClass(obj, cls) {
let Obj = obj;
let objClass = obj.className;
let blank = objClass !== "" ? " " : "";
if (!hasClass(obj, cls)) {
let added = objClass + blank + cls;
Obj.className = added;
}
}

function removeClass(obj, cls) {
let Obj = obj;
let reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
if (hasClass(obj, cls)) {
Obj.className = obj.className.replace(reg, " ");
}
}

转载于:https://www.cnblogs.com/keleyz/p/10794303.html

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