本文分享一個實用範例:用 JavaScript 為表格加上隔行變色、滑鼠移入移出高亮,以及點擊選取效果。這些都能有效提升使用者體驗。
效果說明:
讓表格的奇數行與偶數行呈現不同底色,可避免使用者看資料時串行;滑鼠移在某行時變色、移出還原,讓使用者清楚知道自己正在看哪一列;點擊某行後高亮,方便使用者標記想保留的項目。
實作要點:
i%2 是每個索引與 2 取餘,結果只有 0 和 1 兩種,正好用來判斷奇偶並套用隔行變色;為每行設定 onoff = 1 這個標記,目的是讓點擊後的選取狀態不會被滑鼠移入移出所覆蓋。
程式碼如下:
<!DOCTYPE html> <html> <head> <meta charset="gb2312" /> <title>無標題文檔</title> <style> table{ border-collapse:collapse } table td{ height:26px; font-size:12px; color:#333; border:1px solid #09c; text-align:center; padding:0 10px; } </style> </head> <body> <script> window.onload = function(){ var tables = document.getElementById("tables"); var tables_li = tables.getElementsByTagName("tr"); var i=0; var len = tables_li.length; for(i=0; i<len; i++){ tables_li[i].onoff = 1; tables_li[i].index = i; tables_li[i].style.backgroundColor = i%2?"#ace":""; tables_li[i].onmouseover = function(){ if(this.onoff == 1){ this.style.backgroundColor = "#06c"; } } tables_li[i].onmouseout = function(){ if(this.onoff == 1){ this.style.backgroundColor = this.index%2?"#ace":""; } } tables_li[i].onclick = function(){ if(this.onoff == 1){ this.onoff = 0; this.style.backgroundColor = "#069"; }else{ this.onoff = 1; this.style.backgroundColor = this.index%2?"#ace":""; } } } } </script> <table width="500" border="0" align="center" cellpadding="0" cellspacing="0" id="tables"> <tr> <td>1</td> <td>內容內容</td> </tr> <tr> <td>2</td> <td>內容內容</td> </tr> <tr> <td>3</td> <td>內容內容</td> </tr> <tr> <td>4</td> <td>內容內容</td> </tr> <tr> <td>5</td> <td>內容內容</td> </tr> <tr> <td>6</td> <td>內容內容</td> </tr> <tr> <td>7</td> <td>內容內容</td> </tr> <tr> <td>8</td> <td>內容內容</td> </tr> <tr> <td>9</td> <td>內容內容</td> </tr> <tr> <td>10</td> <td>內容內容</td> </tr> </table> </body> </html>
希望本文所述對大家的 JavaScript 程式設計有所幫助。