hasClass
HTMLElement.prototype.hasClass = function(cln){
let str = this.className;
str = str.replace(/^ +| +$/g,'');
let ary = str.split(/ +/);
cln = cln.replace(/^ +| +$/g,'');
let arr = cln.split(/ +/);
let temp = [];
for(let i = 0; i < arr.length; i++){
ary.indexOf(arr[i]) == -1 ? null : temp.push(arr[i])
}
return temp.length === arr.length
}
複製代碼
HTMLElement.prototype.hasClass = function(cln){
if(!cln.replace(/^ +| +$/g,'').length)return false;
let arr = cln.replace(/^ +| +$/g,'').split(/ +/);
// let ary = this.className.replace(/^ +| +$/g,'').split(/ +/);
let str = this.className;
let flag = true;
for(let i =0; i < arr.length; i++){
let reg = new RegExp(`\\b${arr[i]}\\b`);
// /\bqqq\b/ /(^| +)qqq( +|$)/
if(!reg.test(str)){
flag = false;
break;
}
}
return flag;
}
複製代碼
addClass
HTMLElement.prototype.addClass = function(cln){
if(this.hasClass(cln))return;
let arr = cln.replace(/^ +| +$/g,'').split(/ +/);
let str = this.className;
arr.forEach(item=>{
this.hasClass(item)?null:str += ' '+item
})
str = str.replace(/^ +| +$/g,'').replace(/ +/g,' ')
this.className = str;
}
複製代碼
removeClass
HTMLElement.prototype.removeClass = function(cln){
if(!this.hasClass(cln))return;
let arr = cln.replace(/^ +| +$/g,'').split(/ +/);
let str = this.className;
arr.forEach(item=>{
let reg = new RegExp('\\b'+item+'\\b','g');
str = str.replace(reg,'');
})
str = str.replace(/^ +| +$/g,'').replace(/ +/g,' ')
this.className = str;
}
複製代碼
toggleClass
HTMLElement.prototype.toggleClass = function(cln){
if(this.hasClass(cln)){
this.removeClass(cln)
}else{
this.addClass(cln)
}
}
複製代碼