jquery 表格(鼠标悬停列标题,改变该列的背景色)

时间:2021-03-04 14:46:44

描述:鼠标悬停列标题,改变该列的背景色

HTML:

<table border="1">
            <thead>
                <tr>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>小文</td>
                    <td>20</td>
                    <td>男</td>
                </tr>
                <tr>
                    <td>小李</td>
                    <td>21</td>
                    <td>男</td>
                </tr>
                <tr>
                   <td>小慧</td>
                    <td>21</td>
                    <td>女</td>
                </tr>
                <tr>
                    <td>琪琪</td>
                    <td>19</td>
                    <td>女</td>
                </tr>
                <tr>
                    <td>小勇</td>
                    <td>22</td>
                    <td>男</td>
                </tr>
                <tr>
                    <td>馨儿</td>
                    <td>23</td>
                    <td>女</td>
                </tr>
                <tr>
                    <td>小鹏</td>
                    <td>21</td>
                    <td>男</td>
                </tr>
                <tr>
                    <td>鸭梨山大</td>
                    <td>30</td>
                    <td>男</td>
                </tr>
            </tbody>
        </table>

CSS:

.hover{
                background-color: #00f;
                color: #fff;
            }

jquery:

$('th').hover(function(){
                    //                    获取当前th的索引值
                    var col_index = $(this).index();
                    //                     alert(col_index);
                    //nth-child的参数值从1开始,故索引值加1
                    $('tbody td:nth-child('+(col_index+1)+')').addClass('hover');
                }, function(){
                    //                    移出所有tr子元素的样式
                    $('tbody tr').children().removeClass('hover');
                }); 

截图:

jquery 表格(鼠标悬停列标题,改变该列的背景色)

知识点:

1,index(),详见手册

2,nth-child(index/even/odd/equation),具体详见手册