案例:表格隔行變色(滑鼠划過背景色恢復) <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> * { padding: 0; margin: 0; } .wrap { width ...
案例:表格隔行變色(滑鼠划過背景色恢復)
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> * { padding: 0; margin: 0; } .wrap { width: 500px; margin: 100px auto 0; } table { border-collapse: collapse; border-spacing: 0; border: 1px solid #c0c0c0; width: 500px; cursor: pointer; } th, td { border: 1px solid #d0d0d0; color: #404060; padding: 10px; text-align: center; } th { background-color: #09c; font: bold 16px "微軟雅黑"; color: #fff; } td { font: 14px "微軟雅黑"; } tbody tr { background-color: pink; } </style> </head> <body> <div class="wrap"> <table> <thead> <tr> <th>序號</th> <th>姓名</th> <th>課程</th> <th>成績</th> </tr> </thead> <tbody id="j_tb"> <tr> <td> 1 </td> <td>柳岩</td> <td>語文</td> <td>100</td> </tr> <tr> <td> 2 </td> <td>蒼老師</td> <td>日語</td> <td>100</td> </tr> <tr> <td> 3 </td> <td>鳳姐</td> <td>營銷學</td> <td>100</td> </tr> <tr> <td> 4 </td> <td>芙蓉姐姐</td> <td>數學</td> <td>10</td> </tr> <tr> <td> 5 </td> <td>佐助</td> <td>英語</td> <td>100</td> </tr> <tr> <td> 6 </td> <td>卡卡西</td> <td>體育</td> <td>100</td> </tr> <tr> <td> 7 </td> <td>喬峰</td> <td>體育</td> <td>100</td> </tr> </tbody> </table> </div> <script src="common.js"></script> <script> //獲取所以的行 var trs = my$("j_tb").getElementsByTagName("tr"); for (var i = 0; i < trs.length; i++) { trs[i].style.backgroundColor = i % 2 == 0 ? "white" : "skyblue"; //滑鼠進入 trs[i].onmouseover = mouseoverHandle; //滑鼠離開 trs[i].onmouseout = mouseoutHandle; } //滑鼠進入的時候,先把設置後的顏色保存,等到滑鼠離開再恢復即可 var lastColor = ""; function mouseoverHandle() {//滑鼠進入 lastColor = this.style.backgroundColor; this.style.backgroundColor = "pink"; } function mouseoutHandle() {//滑鼠進入 this.style.backgroundColor = lastColor; } </script> </body> </html>