日期:2014-05-16  浏览次数:20410 次

JavaScript改变表格单元格的背景颜色(修正版)
JavaScript改变表格单元格的背景颜色

示例:
<table id="table"> 
  <tr> 
    <td>111 </td> 
  </tr> 
  <tr> 
    <td>222 </td> 
  </tr> 
  <tr> 
    <td>333 </td> 
  </tr> 
  <tr> 
    <td>444 </td> 
  </tr> 
  <tr> 
    <td>555 </td> 
  </tr> 
</table>

以下source放到<body> </body>间的最后面
<script type="text/javascript"> 
  var tab=new changeColor();
  tab.setId("table"); 
  tab.setMod(3); 
  tab.setColorList("#eee,#ccf,#fff"); 
  tab.setColorOver("#ff0000"); 
  tab.setColor(1);
  tab.goOut();
</script>
=================================================================
以下source放到<head> </head>之间
/*************************************************
功能        : 改变表格单元格的背景颜色 

参数 
id          : 必选。确定变色的表格 
mod         : 可选。表示几次颜色一个循环,默认为2 
colorList   : 可选。里面颜色可用指定的颜色代替,以改变表格背景色 
colorOver   : 可选。鼠标移到表格单元格上时的颜色,默认为灰色 
color       : 可选。以1表示鼠标移动时表格单元格变色,其它数值均不变色 
步骤 
1、指定要变色的表格ID 
2、根据需要选择要更改的参数 
3、输出表格
*************************************************/
function changeColor(){  
  this.id     = "";  
  this.mod    = 2;  
  this.colorList  = "#c5c5c5,#fff";  
  this.colorOver  = "#f5f5f5";  
  this.color    = 1;  
}  
changeColor.prototype.setId=function(id){  
  this.id=id;  
}  
changeColor.prototype.setMod=function(mod){  
  this.mod=mod;  
}  
changeColor.prototype.setColorList=function(colorlist){  
  this.colorList=colorlist;  
}  
changeColor.prototype.setColorOver=function(colorover){  
  this.colorOver=colorover;  
}  
changeColor.prototype.setColor=function(color){  
  this.color=color;  
}  
changeColor.prototype.goOut=function(){  
  id      = this.id;  
  mod     = this.mod;  
  colorList = this.colorList;  
  colorOver = this.colorOver;  
  color   = this.color;  
  var o=document.getElementById(id).getElementsByTagName("tr");  
  var str=colorList.split(",");  
  if(mod<=1){  
    mod=1;  
  }  
  if(mod>str.length){  
    mod=str.length;  
  }  
  if(color!=1){  
    color=0;  
  }  
  for(var i=0; i<o.length; i++){  
    var x=i%mod;  
    if(typeof colorList=="string" && colorList.indexOf(",")!=-1){