javascript制作表格行高亮显示效果

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		table{width: 500px;border: 1px solid gray;border-collapse: collapse;}
		td,th{line-height: 35px;text-align: center;border: 1px solid gray;}
	</style>

	<script type="text/javascript">
		/*
			1.实现表格隔行换色
			2.当鼠标经过任一行时,高亮显示
		*/
	</script>
</head>
<body>
	<table id="tab">
		<thead>
			<tr>
				<th>编号</th>
				<th>姓名</th>
				<th>年龄</th>
				<th>住址</th>
			</tr>
		</thead>
		<tbody id="tb">
			<tr>
				<td>AAAA</td>
				<td>AAAA</td>
				<td>AAAA</td>
				<td>AAAA</td>
			</tr>
			<tr>
				<td>AAAA</td>
				<td>AAAA</td>
				<td>AAAA</td>
				<td>AAAA</td>
			</tr>
			<tr>
				<td>AAAA</td>
				<td>AAAA</td>
				<td>AAAA</td>
				<td>AAAA</td>
			</tr>
			<tr>
				<td>AAAA</td>
				<td>AAAA</td>
				<td>AAAA</td>
				<td>AAAA</td>
			</tr>
			<tr>
				<td>AAAA</td>
				<td>AAAA</td>
				<td>AAAA</td>
				<td>AAAA</td>
			</tr>
		</tbody>
	</table>

	<script type="text/javascript">
		//找到tbody内容
		var tb=document.getElementById('tb').children;

		//创建函数,赋值不同行颜色
		function show(){
				for(var i=0;i<tb.length;i++){
				if (i%2==0) {
					tb[i].style.backgroundColor='blue';
				}else{
					tb[i].style.backgroundColor='pink';
				}
			}
		}

		show();

		//创建鼠标事件
		for(var i=0;i<tb.length;i++){
			//鼠标移动到元素之上事件
			tb[i].onmouseover=function(){
				this.style.backgroundColor='red';
			}
			//鼠标离开事件
			tb[i].onmouseout=function(){
				show();
			}
		}
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_44830974/article/details/89976550
今日推荐