本文實例講述了javascript模擬評分控件實現方法。分享給大家供大家參考。具體實現方法如下:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>動態設置style(評分效果)</title> <script type="text/javascript"> //查找一個元素在數組中的索引位置 function ArrayIndexOf(arr, element) { for (var i = 0; i < arr.length; i++) { if (arr[i] == element) { return i; } } return -1; } function IniEvent() { var tbl = document.getElementById("tblRating"); var tds = tbl.getElementsByTagName("td"); for (var i = 0; i < tds.length; i++) { var td = tds[i]; td.onclick = tdOnClick; td.style.cursor = "pointer"; //設置光標手型 } } function tdOnClick() { var tbl = document.getElementById("tblRating"); var tds = tbl.getElementsByTagName("td"); //查找當前點擊的td的索引 var index = ArrayIndexOf(tds, this); //之前的td改為紅色 for (var i = 0; i <= index; i++) { tds[i].style.background = "red"; } //之後的td改為白色 for (var i = index + 1; i < tds.length; i++) { tds[i].style.background = "white"; } } </script> </head> <body onload="IniEvent()"> <table id="tblRating"> <tr> <td>☆</td> <td>☆</td> <td>☆</td> <td>☆</td> <td>☆</td> </tr> </table> </body> </html>希望本文所述對大家的javascript程序設計有所幫助。