本文實例講述了javascript模擬評分控制項實作方法。分享給大家供大家參考。具體實作方法如下:
<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程式設計有所幫助。