1 <!DOCTYPE HTML>
2 <html lang="en-US">
3 <head>
4 <meta charset="UTF-8">
5 <title>javascript星级评分</title>
6
7 <style type="text/css">
8
9 *{margin:0;padding:0;}
10
11 .wrapper{height:20px;padding:5px;width:130px;margin:100px auto 10px;}
12
13 a{float:left;width:26px;height:20px;background:url(star.png) 0 -20px no-repeat;}
14
15 p{font:24px SimSun;width:130px;margin-left:auto;margin-right:auto;}
16
17 </style>
18 </head>
19 <body>
20 <div class="wrapper">
21
22 <a href="javascript:;"></a>
23 <a href="javascript:;"></a>
24 <a href="javascript:;"></a>
25 <a href="javascript:;"></a>
26 <a href="javascript:;"></a>
27
28 </div>
29
30 <p></p>
31 </body>
32 </html>
33
34 <script type="text/javascript">
35
36 window.onload = function(){
37
38 var star = document.getElementsByTagName('a');
39
40 var oDiv = document.getElementsByTagName('div')[0];
41
42 var temp = 0;
43
44
45
46 for(var i = 0, len = star.length; i < len; i++){
47
48 star[i].index = i;
49
50
51 star[i].onmouseover = function(){
52 clear();
53
54 for(var j = 0; j < this.index + 1; j++){
55
56 star[j].style.backgroundPosition = '0 0';
57
58 }
59
60 }
61
62 star[i].onmouseout = function(){
63 for(var j = 0; j < this.index + 1; j++){
64 star[j].style.backgroundPosition = '0 -20px';
65 }
66 current(temp);
67 }
68
69
70 star[i].onclick = function(){
71 temp = this.index + 1;
72
73 document.getElementsByTagName('p')[0].innerHTML = temp + ' 颗星';
74 current(temp);
75
76 }
77
78 }
79 //清除所有
80 function clear(){
81 for(var i = 0, len = star.length; i < len; i++){
82 star[i].style.backgroundPosition = '0 -20px';
83 }
84 }
85 //显示当前第几颗星
86 function current(temp){
87 for(var i = 0; i < temp; i++){
88 star[i].style.backgroundPosition = '0 0';
89 }
90 }
91
92 };
93
94 </script>