js实现表格隔行变色效果

实现效果:
在这里插入图片描述
代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="http://at.alicdn.com/t/font_3028312_jwhbry8a2fk.css">
    <title>Document</title>
    <style>
        * {
            margin: 0px;
            padding: 0px;
        }

        table {
            width: 500px;
            height: 300px;
            margin: 20px auto;
        }
    </style>
</head>

<body>
    <div>
        <table border="1" style="border-collapse: collapse;">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>城市</th>
                    <th>财富</th>
                    <th>性别</th>
                </tr>
            </thead>
            <tbody class="bg">
                <tr>
                    <td>10001</td>
                    <td>user-1</td>
                    <td>城市-1</td>
                    <td>82830701</td>
                    <td>女</td>
                </tr>
                <tr>
                    <td>10002</td>
                    <td>user-2</td>
                    <td>城市-2</td>
                    <td>82830702</td>
                    <td>男</td>
                </tr>
                <tr>
                    <td>10001</td>
                    <td>user-1</td>
                    <td>城市-1</td>
                    <td>82830701</td>
                    <td>女</td>
                </tr>
                <tr>
                    <td>10002</td>
                    <td>user-2</td>
                    <td>城市-2</td>
                    <td>82830702</td>
                    <td>男</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
<script>
    var trList = document.querySelector("tbody").querySelectorAll("tr");
    // 通过style行内属性来改变
    for (var i = 0; i < trList.length; i++) {
        if (i % 2 == 0) {
            trList[i].style.backgroundColor = "pink";
        } else if (i % 2 != 0) {
            trList[i].style.backgroundColor = "powderblue";
        }

        // 鼠标划入
        trList[i].onmouseover = function () {
            this.bgColor = this.style.backgroundColor
            this.style.backgroundColor = "wheat";
        }

        // 鼠标划出
        trList[i].onmouseout = function () {
            this.style.backgroundColor = this.bgColor;
        }
    }
</script>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值