table 中的tr 行点击 变换颜色背景

    <style>
            table{border-collapse: collapse;border-spacing: 0; width: 100%;}
            table tr th,td{border:1px solid #ccc;text-align: center;}
            table tr th{background:#D4D4D4}
            table tr:hover{background:#fafafa}
            table tbody tr:nth-child(even){background:#f9c}
        </style>
<table id="tableBox">
            <thead>
                <tr style="background: #ccc;">
                <th>姓名</th>
                <th>性别</th>
                <th>年龄</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>张思</td>
                    <td></td>
                    <td>21</td>
                </tr>
                <tr>
                    <td>张天宇</td>
                    <td></td>
                    <td>16</td>
                </tr>
                <tr>
                    <td>李想</td>
                    <td></td>
                    <td>35</td>
                </tr>
            </tbody>
        </table>

<script>
    //js放到table下,才能检测到tr数组 
    var trs = document.getElementById("tableBox").getElementsByTagName("tr");  
   var trs=document.getElementById("tableBox").getElementsByTagName("tr");
       $(function(){
           for(var i=0;i<trs.length;i++){
               trs[i].onmousedown = function(){
                   mousedownclick(this);
               }
           }
       });
       function mousedownclick(obj){
           for(var j=0;j<trs.length;j++){
               if(trs[j]==obj){
                   trs[j].style.background='blue';
               }else{
                   trs[j].style.background='';
               }
           }
       }
</script>

posted @ 2017-06-28 10:21  放荡不羁的春天  阅读(7257)  评论(0编辑  收藏  举报