DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> 表格單元格交錯著色實現思路及代碼
表格單元格交錯著色實現思路及代碼
編輯:關於JavaScript     
【Title】[原]表格單元格交錯著色
【Abstract】以空間換時間,循環確定所著顏色。
【Environment】jQuery
【Author】wintys ([email protected]) http://wintys.cnblogs.com
【Content】:
1、效果
 
2、問題描述
對如下表格中的單元格進行交錯著色。表格中HTML標簽、內容已定。
復制代碼 代碼如下:
<div id="tablecontainer" align="center">
<table style="border-collapse:collapse;" cellspacing="0">
<tbody>
<tr>
<td><a href="http://www.yunyun.com/">TR0-TD0</a></td>
<td><a href="http://www.yunyun.com/">TR0-TD1</a></td>
<td><a href="http://www.yunyun.com/">TR0-TD2</a></td>
<td><a href="http://www.yunyun.com/">TR0-TD3</a></td>
</tr>
<tr>
<td><a href="http://www.yunyun.com/">TR1-TD0</a></td>
<td><a href="http://www.yunyun.com/">TR1-TD1</a></td>
<td><a href="http://www.yunyun.com/">TR1-TD2</a></td>
<td><a href="http://www.yunyun.com/">TR1-TD3</a></td>
</tr>
<tr>
<td><a href="http://www.yunyun.com/">TR2-TD0</a></td>
<td><a href="http://www.yunyun.com/">TR2-TD1</a></td>
<td><a href="http://www.yunyun.com/">TR2-TD2</a></td>
<td><a href="http://www.yunyun.com/">TR2-TD3</a></td>
</tr>
<tr>
<td><a href="http://www.yunyun.com/">TR3-TD0</a></td>
<td><a href="http://www.yunyun.com/">TR3-TD1</a></td>
<td><a href="http://www.yunyun.com/">TR3-TD2</a></td>
<td><a href="http://www.yunyun.com/">TR3-TD3</a></td>
</tr>
</tbody>
</table>
</div>

3、實現
3.1、CSS
復制代碼 代碼如下:
<style type="text/css">
.tableitem0 {
background: none repeat scroll 0 0 #F65314;
color: #FFFFFF;
}
.tableitem1 {
background: none repeat scroll 0 0 #7CBB00;
color: #FFFFFF;
}
.tableitem2 {
background: none repeat scroll 0 0 #00A1F1;
color: #FFFFFF;
}
.tableitem3 {
background: none repeat scroll 0 0 #FFBB00;
color: #FFFFFF;
}
#tablecontainer td {
padding: 5px;
}
.tableitem {
width: 15%;
}
.tableitem a {
display: block;
font-size: 18px;
height: 35px;
margin: 0 auto;
padding: 15px 20px;
text-align: center;
border-bottom:none;
}
.tableitem a:hover, .tableitem a:visited {
color: #FFFFFF !important;
}
.tableitem a:hover, .tableitem a:active{
opacity: 0.8;
}
</style>

3.2、JS代碼
復制代碼 代碼如下:
<script type="text/javascript">
function setTableStyle(){
$("#tablecontainer tr").each(function(i){//獲得所有的tr,進行each循環遍歷,並對每個進行操作
var tr = $(this);//得到本次循環裡的這個tr
setTableItemStyle(tr,i%4);//每行四個單元格,四種顏色循環交錯著色。
});
}
function setTableItemStyle(tr,base){
//【重點】:以空間換時間,循環確定所著顏色。
var tableitem = ["tableitem0","tableitem1","tableitem2","tableitem3","tableitem0","tableitem1","tableitem2"];
for(var i = 0; i < 4;i ++){
var td = tr.children("td").eq(i);
var td_a = td.find("a");
td.addClass("tableitem");
//【重點】:base確定起始顏色,i確定本次需要著色的單元格。
td_a.addClass(tableitem[base + i]);
}
}
$(function(){
setTableStyle();
});
</script>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved