DOM之表格隔行换色

废话不多说,先看效果图:
DOM之表格隔行换色_第1张图片
看代码:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            width: 800px;
            margin: 100px auto;
            padding: 0;
            font-size: 14px;
        }
        
        thead tr {
            height: 32px;
            text-align: center;
            background-color: rgba(161, 228, 169, 0.541);
        }
        
        tbody tr {
            height: 30px;
            text-align: center;
        }
        
        td {
            border-bottom: 1px solid #ccc;
            font-size: 12px;
        }
        
        .bg {
            background-color: rgba(128, 212, 245, 0.658);
        }
    </style>
</head>

<body>
    <table>
        <thead>
            <tr>
                <th>编号</th>
                <th>姓名</th>
                <th>年龄</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>张三</td>
                <td>22</td>
            </tr>
            <tr>
                <td>2</td>
                <td>李四</td>
                <td>25</td>
            </tr>
            <tr>
                <td>3</td>
                <td>王五</td>
                <td>27</td>
            </tr>
            <tr>
                <td>4</td>
                <td>赵六</td>
                <td>29</td>
            </tr>
            <tr>
                <td>5</td>
                <td>田七</td>
                <td>30</td>
            </tr>
            <tr>
                <td>6</td>
                <td>汾九</td>
                <td>20</td>
            </tr>
        </tbody>
    </table>
    <script>
        // 1.获取元素,获取tbody里面所有的行
        var trs = document.querySelector('tbody').querySelectorAll('tr');
        //2.利用循环注册事件
        for (var i = 0; i < trs.length; i++) {
            // 3.鼠标经过事件onmouseover
            trs[i].onmouseover = function() {
                    this.className = 'bg';
                }
                //4.鼠标离开事件onmouseout
            trs[i].onmouseout = function() {
                this.className = '';
            }
        }
    </script>
</body>

</html>

你可能感兴趣的:(前端,js,dom)