jquery滑鼠移入變色移出恢復
阿新 • • 發佈:2018-12-13
一、需求說明
現需要對一個表格的內容部分做下高亮處理:當滑鼠放到這一行時,背景色發生改變;當滑鼠移出這一行時,恢復這一行的原有背景色。如下圖,原來是除了首行以外,帶序號的內容部分,奇偶行背景色交替變化,當滑鼠放到第1行時,看到下圖的樣式,移出該行後,恢復原樣。
二、程式碼實現
table及樣式部分:
<style type="text/css"> #studentTable th,td{ border: 1px solid black; } #studentTable tbody tr:nth-child(odd) { background-color:#F2F2F2; } </style> <table id="studentTable" style="border-collapse: collapse;"> <thead> <tr> <th>序號</th> <th>姓名</th> <th>年齡</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>張三</td> <td>10</td> </tr> <tr> <td>2</td> <td>李四</td> <td>20</td> </tr> <tr> <td>3</td> <td>王五</td> <td>30</td> </tr> <tr> <td>4</td> <td>趙六</td> <td>40</td> </tr> <tr> <td>5</td> <td>錢七</td> <td>50</td> </tr> </tbody> </table>
關鍵點:1.給table新增邊框 2.奇偶行顏色交替
js程式碼部分:
<script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.js"></script> <script> $(function () { var oldColor = ""; $("#studentTable tbody tr").mouseover(function () { oldColor = $(this).css("background-color"); $(this).css("background-color","#d9e8fb"); }).mouseout(function () { $(this).css("background-color",oldColor); }); }); </script>
關鍵點:
弄清實現思路:移入時需要a.獲取該行原有背景色 b.給該行新增新的背景色;移出時,恢復改行原有背景色
參考: