描述:鼠標懸停列標題,改變該列的背景色
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'); });
截圖:
知識點:
1,index(),詳見手冊
2,nth-child(index/even/odd/equation),具體詳見手冊