JS——高级各行换色
Posted 站错队了同志
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS——高级各行换色相关的知识,希望对你有一定的参考价值。
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——高级各行换色的主要内容,如果未能解决你的问题,请参考以下文章