原生js模拟jquery中的addClass和removeClass方法

时间:2022-01-04 23:29:44

js代码:

//添加类
function addClass(obj,className) {
if(obj.className == '') {
//如果没有class
obj.className = className;
}else {
var strClass = obj.className;
var arrClass = strClass.split(' ');
var arr = [];
var index = arrIndex(arrClass,className);
if(index == -1) {
//如果不存在class
arr.push(className);
obj.className += ' ' + arr.join(' ');
}
}
}

//移除类
function removeClass(obj,className) {
if(obj.className == '') {
alert('该对象没有class');
}else {
var arrClass = obj.className.split(' ');
console.log(arrClass);
var index = arrIndex(arrClass,className);
if(index != -1) {
//如果该对象已经存在className
arrClass.splice(index,1);
obj.className = arrClass.join(' ');
}
}
}

//查找是否存在相同class

function arrIndex(arrClass,a) {
for(var i = 0; i<arrClass.length; i++) {
if(arrClass[i] == a) {
return i
}
}
return -1;
}