1. 程式人生 > >js實現單雙行以不同顏色顯示

js實現單雙行以不同顏色顯示

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=gb3212">
		<title>單雙行顯示不同的顏色</title>
		<!--下面為javascript程式碼-->
		<script type = "text/javascript">
						window.onload = function color(){//視窗載入時呼叫
				var table = document.getElementById("person");//根據table的 id 屬性值獲得物件
				var rows = table.getElementsByTagName("tr");//獲取table型別的tr元素的列表
				for(var i = 0; i < rows.length; i++){
				 	if(i % 2 == 0){
				  		rows[i].style.backgroundColor = "#EAF2D3";//偶數行時背景色為#EAF2D3
				    }
				    else{
				     	rows[i].style.backgroundColor = "White";//單數行時背景色為white
				 	}
				}
			}
		</script>
		<!--下面為css程式碼-->
		<style type = "text/css">
			#person
				{
					border-style:1px solid;
					border-color:blue;
					font-weight:bold;
					font-family:楷體,Arial, Helvetica, sans-serif;
					border-collapse:collapse;
					margin:auto;
				}
			#person th 
				{
					border:1px solid;
					padding:3px 7px 2px 7px;
					background-color:#A7C942;
					color:#ffffff;
					text-align:center;
				}
			#person td 
				{
					border-style:solid;
					border-width:1px;
					text-align:center;
				}
		</style>
	</head>
	<body>
		<table id = "person" align = "center" width = "90%" height = "200">
			<tr>
				<th>姓名</th>
				<th>性別</th>
				<th>電話</th>
				<th>愛好</th>
			</tr>
			<tr>
				<td>張三</td>
				<td>男</td>
				<td>33333333</td>
				<td>睡覺</td>
			</tr>
			<tr>
				<td>李四</td>
				<td>女</td>
				<td>44444444</td>
				<td>旅遊</td>
			</tr>
			<tr>
				<td>王五</td>
				<td>女</td>
				<td>55555555</td>
				<td>購物</td>
			</tr>
			<tr>
				<td>趙六</td>
				<td>男</td>
				<td>66666666</td>
				<td>看美女</td>
			</tr>
		</table>
	</body>
</html>