经过大大指点,用replace写确定简单了许多。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>添加删除元素的className</title> <style type="text/css"> .box{ width:100px; height:100px; background:#C33;} </style> <script type="text/javascript"> window.onload=function(){ var box=document.getElementById('box'); addClassName(box,'aa'); addClassName(box,'bb'); addClassName(box,'cc'); addClassName(box,'dd'); delClassName(box,'cc') delClassName(box,'box') }; function addClassName(obj,className){ if(obj.className==''){ obj.className=className; }else{ obj.className+=' '+className; } } function delClassName(obj,className){ className=className; var currentClassName=obj.className; if(currentClassName!=''){ var nowClassName=currentClassName.replace(className,''); obj.className=nowClassName; } } </script> </head> <body> <div class="box" id="box"></div> </body> </html>