<div id="d3" class="cur"></div>
1 var mylibs = (function(){ 2 var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, 3 core_trim = String.prototype.trim, 4 core_rspace = /\s+/, 5 rclass = /[\t\r\n]/g; 6 7 var trim = function(text){ 8 if(core_trim && !core_trim.call("\uFEFF\xA0")){ 9 return text == null ? 10 "" : 11 core_trim.call(text); 12 }else{ 13 return text == null ? 14 "" : 15 (text + "").replace(rtrim, ""); 16 } 17 }; 18 19 return { 20 addClass:function(elem,value){ 21 var classNames,setClass; 22 23 if (!value || typeof value !== "string") return; 24 if (elem.nodeType !== 1) return; 25 26 classNames = value.split(core_rspace); 27 28 if (!elem.className && classNames.length === 1){ 29 elem.className = value; 30 }else{ 31 setClass = " " + elem.className + " "; 32 33 for (var i = 0; i < classNames.length; i++){ 34 if (setClass.indexOf(" " + classNames[ i ] + " ") < 0) 35 setClass += classNames[ i ] + " "; 36 } 37 elem.className = trim(setClass); 38 } 39 }, 40 removeClass:function(elem,value){ 41 42 var removes,className; 43 44 if ((!value || typeof value !== "string") && value !== undefined) return; 45 if (elem.nodeType !== 1 || !elem.className) return; 46 47 removes = (value || "").split(core_rspace); 48 className = (" " + elem.className + " ").replace(rclass," "); 49 50 // loop over each item in the removal list 51 for (var i=0;i<removes.length;i++){ 52 // Remove until there is nothing to remove, 53 while (className.indexOf(" " + removes[i] + " ") >= 0) 54 className = className.replace(" " + removes[i] + " "," "); 55 } 56 elem.className = value ? trim(className) : ""; 57 }, 58 toggleClass:function(elem,value,stateVal){ 59 var type = typeof value, 60 isBool = typeof stateVal === "boolean"; 61 62 if (type !== "string") return; 63 64 // toggle individual class names 65 var className, 66 i = 0, 67 state = stateVal, 68 classNames = value.split(core_rspace); 69 70 while ((className = classNames[ i++ ])){ 71 // check each className given, space separated list 72 state = isBool ? state : !this.hasClass(elem,className); 73 (state ? this[‘addClass‘] : this[‘removeClass‘])(elem,className); 74 } 75 }, 76 hasClass:function(elem,selector){ 77 var className = " " + selector + " "; 78 if (elem.nodeType === 1 && (" " + elem.className + " ").replace(rclass," ").indexOf(className) >= 0) 79 return true; 80 return false; 81 } 82 }; 83 })(); 84 85 var dom = document.getElementById(‘d3‘); 86 mylibs.addClass(dom,‘red‘); 87 mylibs.removeClass(dom,‘cur‘); 88 mylibs.toggleClass(dom,‘red cur‘);
时间: 2024-10-28 23:03:36