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

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 if(arrClass[i] == a) {
return i
}
}
return -1;
}

 

转载于:https://www.cnblogs.com/ysyblue/p/10135693.html

你可能感兴趣的:(原生js模拟jquery中的addClass和removeClass方法)