1、获取tbody下的子元素
2、注册鼠标覆盖事件时存储当时的背景颜色,注册鼠标离开事件时把存储的颜色赋值注册事件对象
<!DOCTYPE html><html><head lang="en"> ???<meta charset="UTF-8"> ???<title></title> ???<style> ???????* { ???????????padding: 0; ???????????margin: 0; ???????????text-align: center; ???????} ???????div { ???????????width: 300px; ???????????margin: 50px auto; ???????} ???????table { ???????????width: 300px; ???????????height: 200px; ???????????border: 1px solid #ccc; ???????????border-collapse: collapse; ???????} ???????th { ???????????background-color: #09c; ???????????font: bold 16px "微软雅黑"; ???????????color: #fff; ???????} ???????th, td { ???????????border: 1px solid #d0d0d0; ???????????color: #404060; ???????????padding: 10px; ???????} ???????tbody tr { ???????????background-color: #f0f0f0; ???????????cursor: pointer; ???????} ???</style></head><body> ???<div> ???????<table> ???????????<thead> ???????????????<tr> ???????????????????<th>序号</th> ???????????????????<th>姓名</th> ???????????????????<th>课程</th> ???????????????????<th>成绩</th> ???????????????</tr> ???????????</thead> ???????????<tbody> ???????????????<tr> ???????????????????<td>1</td> ???????????????????<td>你好</td> ???????????????????<td>你好</td> ???????????????????<td>你好</td> ???????????????</tr> ???????????????<tr> ???????????????????<td>2</td> ???????????????????<td>你好</td> ???????????????????<td>你好</td> ???????????????????<td>你好</td> ???????????????</tr> ???????????????<tr> ???????????????????<td>3</td> ???????????????????<td>你好</td> ???????????????????<td>你好</td> ???????????????????<td>你好</td> ???????????????</tr> ???????????????<tr> ???????????????????<td>4</td> ???????????????????<td>你好</td> ???????????????????<td>你好</td> ???????????????????<td>你好</td> ???????????????</tr> ???????????????<tr> ???????????????????<td>5</td> ???????????????????<td>你好</td> ???????????????????<td>你好</td> ???????????????????<td>你好</td> ???????????????</tr> ???????????????<tr> ???????????????????<td>6</td> ???????????????????<td>你好</td> ???????????????????<td>你好</td> ???????????????????<td>你好</td> ???????????????</tr> ???????????</tbody> ???????</table> ???</div> ???<script> ???????var tbody = document.getElementsByTagName("tbody")[0]; ???????var trs = tbody.children; ???????var color = ""; ???????for (var i = 0; i < trs.length; i++) { ???????????if (i % 2 !== 0) { ???????????????trs[i].style.backgroundColor = "#c3c3c3"; ???????????} ????????????trs[i].onmouseover = function () { ???????????????color = this.style.backgroundColor; ???????????????this.style.backgroundColor = "#fff"; ???????????} ???????????trs[i].onmouseout = function () { ???????????????this.style.backgroundColor = color; ???????????} ???????} ?????</script></body></html>
JS——高级各行换色
原文地址:http://www.cnblogs.com/wuqiuxue/p/7880574.html