DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> WEB網站前端 >> WEB前端代碼
jQuery + CSS 實作表格隔行換色
編輯:WEB前端代碼     

表格資料一多就容易看錯行,隔行換色(斑馬紋)是最經典的解法。這個範例用 jQuery 的 :odd 選擇器自動為奇數行加上樣式,HTML 完全不用改。

先看效果:

這個是第1行的文字  
這個是第2行的文字  
這個是第3行的文字  
這個是第4行的文字  
這個是第5行的文字  
這個是第6行的文字  
這個是第7行的文字  
這個是第8行的文字  
這個是第9行的文字  
這個是第10行的文字  

原始碼

<style>
.listtd{background-color:#999900}
</style>

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="list">
<tr><td height="20">這個是第1行的文字</td><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td height="20">這個是第2行的文字</td><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td height="20">這個是第3行的文字</td><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td height="20">這個是第4行的文字</td><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td height="20">這個是第5行的文字</td><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td height="20">這個是第6行的文字</td><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td height="20">這個是第7行的文字</td><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td height="20">這個是第8行的文字</td><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td height="20">這個是第9行的文字</td><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td height="20">這個是第10行的文字</td><td>&nbsp;</td><td>&nbsp;</td></tr>
</table>

<script type="text/javascript" src="https:///keleyi/pmedia/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function(){
$("#list tr:odd").addClass('listtd');
});;
</script>

重點說明

$(function(){...}) 是 DOM ready 的簡寫,確保表格已經存在於文件上才去操作它。接著 $("#list tr:odd") 選出 #list 底下所有索引為奇數的 tr,:odd 由 jQuery 提供(索引從 0 起算,所以實際上色的會是第 2、4、6… 個 tr)。最後 addClass('listtd') 把樣式掛上去。

这种做法的好处是 HTML 保持乾淨,後端輸出資料時不必自己判斷奇偶。缺點則是依賴 JavaScript:若腳本沒載入或執行失敗,斑馬紋就會消失。

現代的替代方案是純 CSS:tr:nth-child(odd) { background-color:#999900; } 一行就能完成,不需要 jQuery,也不需要等 DOM ready。若你的專案已不再支援舊版 IE,直接採用 CSS 版本會更輕量、更可靠。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved