addClass, removeClass, toggleClass(从jquery中抠出来)

时间:2023-02-02 09:58:08
<div id="d3" class="cur"></div>
 var mylibs = (function(){
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
core_trim = String.prototype.trim,
core_rspace = /\s+/,
rclass = /[\t\r\n]/g; var trim = function(text){
if(core_trim && !core_trim.call("\uFEFF\xA0")){
return text == null ?
"" :
core_trim.call(text);
}else{
return text == null ?
"" :
(text + "").replace(rtrim, "");
}
}; return {
addClass:function(elem,value){
var classNames,setClass; if (!value || typeof value !== "string") return;
if (elem.nodeType !== 1) return; classNames = value.split(core_rspace); if (!elem.className && classNames.length === 1){
elem.className = value;
}else{
setClass = " " + elem.className + " "; for (var i = 0; i < classNames.length; i++){
if (setClass.indexOf(" " + classNames[ i ] + " ") < 0)
setClass += classNames[ i ] + " ";
}
elem.className = trim(setClass);
}
},
removeClass:function(elem,value){ var removes,className; if ((!value || typeof value !== "string") && value !== undefined) return;
if (elem.nodeType !== 1 || !elem.className) return; removes = (value || "").split(core_rspace);
className = (" " + elem.className + " ").replace(rclass," "); // loop over each item in the removal list
for (var i=0;i<removes.length;i++){
// Remove until there is nothing to remove,
while (className.indexOf(" " + removes[i] + " ") >= 0)
className = className.replace(" " + removes[i] + " "," ");
}
elem.className = value ? trim(className) : "";
},
toggleClass:function(elem,value,stateVal){
var type = typeof value,
isBool = typeof stateVal === "boolean"; if (type !== "string") return; // toggle individual class names
var className,
i = 0,
state = stateVal,
classNames = value.split(core_rspace); while ((className = classNames[ i++ ])){
// check each className given, space separated list
state = isBool ? state : !this.hasClass(elem,className);
(state ? this['addClass'] : this['removeClass'])(elem,className);
}
},
hasClass:function(elem,selector){
var className = " " + selector + " ";
if (elem.nodeType === 1 && (" " + elem.className + " ").replace(rclass," ").indexOf(className) >= 0)
return true;
return false;
}
};
})(); var dom = document.getElementById('d3');
mylibs.addClass(dom,'red');
mylibs.removeClass(dom,'cur');
mylibs.toggleClass(dom,'red cur');