描述:通过javascript控制表格的奇数行和偶数行的颜色不一样,鼠标经过的时候,颜色变成白色,鼠标离开,颜色恢复原来的颜色。并且封装好了函数,适用于网页中所有的表格。
实现代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>高级隔行变色</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        .form{
            width: 500px;
            margin: 100px auto 0;
        }
        table{
            border-collapse: collapse;
            border-spacing: 0;
            border: 1px solid #404060;
            width: 500px;
            text-align: center;
        }
        th,td{
            border: 1px solid #404060;
            padding: 10px;
        }
        th {
            background-color: #09c;
            font: bold 16px "微软雅黑";
            color: #fff;
        }
    </style>
</head>
<body>
    <div class="form">
        <table>
            <thead>
                <tr>
                    <th>学号</th>
                    <th>姓名</th>
                    <th>成绩</th>
                </tr>
            </thead>
            <tbody class="target">
                <tr>
                    <td>001</td>
                    <td>赵武</td>
                    <td>100</td>
                </tr>
                <tr>
                    <td>002</td>
                    <td>赵武</td>
                    <td>100</td>
                </tr>
                <tr>
                    <td>003</td>
                    <td>赵武</td>
                    <td>100</td>
                </tr>
                <tr>
                    <td>004</td>
                    <td>赵武</td>
                    <td>100</td>
                </tr>
                <tr>
                    <td>005</td>
                    <td>赵武</td>
                    <td>100</td>
                </tr>
                <tr>
                    <td>006</td>
                    <td>赵武</td>
                    <td>100</td>
                </tr>
                <tr>
                    <td>007</td>
                    <td>赵武</td>
                    <td>100</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>
<script>
    var tbody = document.getElementsByClassName("target");
    for(var i = 0;i<tbody.length;i++){
        changeColor(tbody[i]);
    }
    function changeColor(ele) {
        var trArr = ele.children;

        for (var i = 0;i<trArr.length;i++){
            if(i%2!==0){
                trArr[i].style.background = "#a3a3a3";
            }else{
                trArr[i].style.background = "#ccc";
            }
            var color = "";
            trArr[i].onmouseover = function () {
                color = this.style.background;
                this.style.background = "#fff";
            }
            trArr[i].onmouseout = function () {
                this.style.background = color;
            }
        }
    }

</script>
Last modification:April 12, 2018
If you think my article is useful to you, please feel free to appreciate