原生js封装addClass removeClass hasClass

// 添加类
function addClass(obj, cls) {
var obj_class = obj.className;  
blank = (obj_class != "") ? " " : "";  
added = obj_class + blank + cls;  
obj.className = added;    
 }

//移除class
function removeClass(obj, cls) {
var obj_class = " " + obj.className + " ";
//将多余的空格替换为一个空格
obj_class = obj_class.replace(/(\s+)/gi, " ");

//将原来的class替换为首尾加空格的class
removed = obj_class.replace(" " + cls + " ", " ");
 
//去掉首尾空格
removed = removed.replace(/(^\s+)|(\s+$)/g, "");
obj.className = removed;
}
//判断是否有class
function hasClass(obj, cls) {
var obj_class = obj.className;
var obj_class_list = obj_class.split(" ");
var x = 0;
for(x in obj_class_list) {
if(obj_class_list[x] == cls) {
return false;
} else{
return true
}
}  
}
//var div1 = document.getElementById("div1");  
addClass(div1, "btn1");
removeClass(div1,"btn1");
if(hasClass(div1,"btn4")){
console.log("没有");
}else{
console.log("有");
}

你可能感兴趣的:(js,前端学习)