【Web前端】【JavaScript】实现表格隔行变色

方法1:原生JavaScript

设置CSS

    table td{
        border:red solid 1px;
    }
.tr1{
    color:white;
        background: black;
    }
.tr2{
    color:black;
        background: white;
    }
    .tr2:hover{
        color:red;
        background: yellow;
    }

设置JavaScript

(1)获取tr标签

 var ctr=document.getElementById("tab").getElementsByTagName("tr");

(2)使用循环

 function fun(){
            for(i=0;i<ctr.length;i++){
                ctr[i].className=((i+1)%2>0)?"tr1":"tr2";
            }
        }

(3)调用js

window.onload=fun;

【Web前端】【JavaScript】实现表格隔行变色

注意事项:该JavaScript代码需要在加载完毕后执行。

点击查看完整代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>index</title>
<style>
table td{
        border:red solid 1px;
    }
.tr1{
    color:white;
        background: black;
    }
.tr2{
    color:black;
        background: white;
    }
.tr2:hover{
        color:red;
        background: yellow;
    }
</style>
    
</head>

<body>
    <table id="tab">
        <tr>
            <td>mllt</td>
            <td>mllt</td>
            <td>mllt</td>
        </tr>
        <tr>
            <td>mllt</td>
            <td>mllt</td>
            <td>mllt</td>
        </tr>
        <tr>
            <td>mllt</td>
            <td>mllt</td>
            <td>mllt</td>
        </tr>
        <tr>
            <td>mllt</td>
            <td>mllt</td>
            <td>mllt</td>
        </tr>
        <tr>
            <td>mllt</td>
            <td>mllt</td>
            <td>mllt</td>
        </tr>
        <tr>
            <td>mllt</td>
            <td>mllt</td>
            <td>mllt</td>
        </tr>
        <tr>
            <td>mllt</td>
            <td>mllt</td>
            <td>mllt</td>
        </tr>
        <tr>
            <td>mllt</td>
            <td>mllt</td>
            <td>mllt</td>
        </tr>
        <tr>
            <td>mllt</td>
            <td>mllt</td>
            <td>mllt</td>
        </tr>
        <tr>
            <td>mllt</td>
            <td>mllt</td>
            <td>mllt</td>
        </tr>
    </table>
</body>
    <script>
        var ctr=document.getElementById("tab").getElementsByTagName("tr");
        function fun(){
            for(i=0;i<ctr.length;i++){
                ctr[i].className=((i+1)%2>0)?"tr1":"tr2";
            }
        }
    window.onload=fun;
    </script>
</html>

上一篇:Qt绘制时钟界面


下一篇:Pyhon程序员都在用到一个小而美的代码格式化工具竟是它