核心只要两行即可实现添加或移除className

<!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=utf-8" />
<title>核心只要两行即可实现添加或移除className</title>
<script type="text/javascript">
 function removeClass(value){
  var kls,reg=1>0 &&(kls=this.className,reg=new RegExp('(^| )'+value+'( |$)'),reg.test(this.className) && (this.className=(kls.replace(reg,'$1')).replace(/ $/,'')));
  return this;
 };
 function addClass(value){
  var reg=1>0 &&(reg=new RegExp('(^| )'+value+'( |$)'),reg.test(this.className) || (this.className==='' ? (this.className=value) : (this.className+=(' '+value))));
  return this;
 };
  
 ///removeClass.call(document.getElementById('abc'),'new');
 //addClass.call(document.getElementById('abc'),['new saw try']) 一次添加多个样式
 addClass.call(addClass.call(removeClass.call(document.getElementById('abc'),'new'),'game'),'beta');
 </script>
</head>
<body>
<div id="abc" class="same new yes">1111111</div> 
</body>
</html>

posted @ 2011-05-06 16:40  moxie  阅读(236)  评论(0编辑  收藏  举报