1. 程式人生 > >JS——高級各行換色

JS——高級各行換色

你好 () es2017 doc var 顏色 out point char

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——高級各行換色