当前位置: 代码迷 >> Web前端 >> 给目标元素增添className-addClass
  详细解决方案

给目标元素增添className-addClass

热度:180   发布时间:2012-11-08 08:48:11.0
给目标元素添加className-addClass

api的应用场景是:给目标元素添加className

?

?

关于className的资料:http://zhangyaochun.iteye.com/blog/1456976

关于ZYC.dom.g请看这里:http://zhangyaochun.iteye.com/blog/1439262

?

简单描述:

?? ? ? ? ? ? ? ? ?如果需要一次调用添加多个class只需用空白符分割:如'red yellow black' ? ? ?

?

?

/*
*addClass-add the className to the element*
*@function*
*@param {string||HTMLElement} element*
*@param {string} className---it can add more than one className,split each other by whitespace*
*@return {HTMLElement} element
*@remark the className is legal or not *
*you can reference in http://www.w3.org/TR/CSS2/syndata.html*
*/
ZYC.dom.addClass = function(element,className){
         element = ZYC.dom.g(element);
	 //must flow the rule ---split each other by whitespace(one or more)
	 //and the whitespace do not just space(制表符或者换行符)
	 var classArray =className.split(/\s+/),
	     result = element.className,  //element old className
		 i =0,
		 classMatch = " "+result+" ",  //used to check if has then decide if add
		 _length=classArray.length;
	 for(;i<_length;i++){
         if(classMatch.indexOf(" "+classArray[i]+" ") <0){
		    //if classArray[i] is new add it
			//and attention (result ? " ":"") if element old className is empty
		    result += (result ? " ":"") + classArray[i];
		 }		 
     }
	 element.className = result;
	 return element;
};