封装addClass()和removeClass()方法

function addClass(element,new_name){

if(!element||!new_name) return false;

if(element.className){

var old_name=element.className;

element.className=old_name+" "+new_name;

}else{

element.className=new_name;

}

return true;

}

var oDiv=document.getElementsByTagName("div")[0];

addClass(oDiv,"div2")
function removeClass(element, class_name) {

if(!element || !class_name) return false;

if (!element.className) return false;

var all_names = element.className.split(" ");

for (var i = 0; i < all_names.length; i++) {

if (all_names[i] === class_name) {

all_names.splice(i, 1);

element.className = "";

for (var j = 0; j < all_names.length; j++) {

element.className += " ";

element.className += all_names[j];

}

return true;

}

}

}

 removeClass(oDiv,"div2");

 

你可能感兴趣的:(封装addClass()和removeClass()方法)