第一種:鼠標經過時table表格中的顏色根據奇偶行改變不同的顏色
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script type="text/javascript"> 7 function changeOver(elementId){ 8 //聲明指定相關表元素 9 var table1 = document.getElementById("table1").children[0]; 10 //for循環語句 11 for(var i=0;i<table1.children.length;i++){ 12 //if判斷語句 13 if(table1.children[i]==elementId){ 14 //奇數行 15 if(i%2==1) 16 //當鼠標覆蓋到表格奇數行時,相關單元格背景色變為#CCCCCC色 17 elementId.style.background="red"; 18 //偶數行 19 else 20 //當鼠標覆蓋到表格偶數數行時,相關單元格背景色變為#F2F2F2色 21 elementId.style.background="green"; 22 } 23 } 24 } 25 //當鼠標離開相關單元格時所觸發的事件 26 function changeOut(elementId){ 27 //當鼠標離開相關表格相關行時,其相關行背景色變為#FFFFFF色 28 elementId.style.background="#FFFFFF"; 29 } 30 31 32 </script> 33 <style type="text/css"> 34 /*表格的樣式*/ 35 table{ 36 width: 200px; 37 height: 400px; 38 border: 1px solid; 39 } 40 tr td{ 41 width: 100px; 42 height: 50px; 43 border: 1px solid; 44 } 45 </style> 46 </head> 47 <body> 48 <!--onmouseover鼠標經過時觸發的函數,onmouseout鼠標離開時觸發的函數--> 49 <table id="table1" > 50 <tr onmouseover="changeOver(this)" onmouseout="changeOut(this)"> 51 <td >1</td> 52 </tr> 53 <tr onmouseover="changeOver(this)" onmouseout="changeOut(this)"> 54 <td>2</td> 55 </tr> 56 <tr onmouseover="changeOver(this)" onmouseout="changeOut(this)"> 57 <td>3</td> 58 </tr> 59 <tr onmouseover="changeOver(this)" onmouseout="changeOut(this)"> 60 <td>4</td> 61 </tr> 62 <tr onmouseover="changeOver(this)" onmouseout="changeOut(this)"> 63 <td>5</td> 64 </tr> 65 <tr onmouseover="changeOver(this)" onmouseout="changeOut(this)"> 66 <td>6</td> 67 </tr> 68 <tr onmouseover="changeOver(this)" onmouseout="changeOut(this)"> 69 <td>7</td> 70 </tr> 71 <tr onmouseover="changeOver(this)" onmouseout="changeOut(this)"> 72 <td>8</td> 73 </tr> 74 75 </table> 76 </body> 77 </html>
第二種:直接用css發生改變,使用了偽類選擇器nth-child
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
/*奇數改變的顏色*/
tr:nth-child(odd){background-color:#FFE4C4;}
/*偶數改變的顏色*/
tr:nth-child(even){background-color:#F0F0F0;}
/*table樣式*/
table{
width: 200px;
height: 400px;
border: 1px solid;
}
/*tr.td的樣式*/
tr td{
width: 100px;
height: 50px;
border: 1px solid;
}
</style>
</head>
<body>
<!--設計的一個簡單表格-->
<table id="table1" >
<tr>
<td >1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<td>4</td>
</tr>
<tr>
<td>5</td>
</tr>
<tr >
<td>6</td>
</tr>
<tr >
<td>7</td>
</tr>
<tr>
<td>8</td>
</tr>
</table>
</body>
</html>
