首页 > 代码库 > 购物车星星评分

购物车星星评分

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title>星星</title>
 6     <script type="text/javascript">
 7         var ifping=false;//增加一个全局变量控制,让鼠标指向星星有滑动效果
 8         window.onload= function () {
 9             //首先获取img元素对象
10             var imgdoms = document.getElementsByTagName("img");
11             //通过获取到的对象数组 循环遍历获得鼠标指向的索引值
12             for (var i = 0; i < imgdoms.length; i++) {
13                 imgdoms[i].setAttribute("index", i + 1);//计算总分,+1是因为索引从零开始
14 
15                 imgdoms[i].onmouseover = function () {//经过点击事件
16                     if (!ifping) {
17                         var j = event.srcElement.getAttribute("index");//当前事件源 :鼠标指向的索引
18                         for (var left = 0; left < j; left++) {//给左边的星星换图片,原理是利用setattribute给元素添加内容
19                             imgdoms[left].setAttribute("src", "images/star-on.png")
20                         }
21                         for (var right = j; right < imgdoms.length; right++) {//同理处理右边的星星
22                             imgdoms[right].setAttribute("src", "images/star-off.png")
23                         }
24                         document.getElementById("span01").innerHTML = j;//给span元素赋值
25                     }
26                 }
27 
28                 imgdoms[i].onclick = function () {//经过点击事件
29                     if (!ifping) {
30                         var j = event.srcElement.getAttribute("index");//当前事件源 :鼠标指向的索引
31                         for (var left = 0; left < j; left++) {//给左边的星星换图片,原理是利用setattribute给元素添加内容
32                             imgdoms[left].setAttribute("src", "images/star-on.png")
33                         }
34                         for (var right = j; right < imgdoms.length; right++) {//同理处理右边的星星
35                             imgdoms[right].setAttribute("src", "images/star-off.png")
36                         }
37                         document.getElementById("span01").innerHTML = j;//给span元素赋值
38                     }
39                 }
40             }
41         }
42     </script>
43 </head>
44 <body>
45 <img src="http://www.mamicode.com/images/star-off.png"/>
46 <img src="http://www.mamicode.com/images/star-off.png"/>
47 <img src="http://www.mamicode.com/images/star-off.png"/>
48 <img src="http://www.mamicode.com/images/star-off.png"/>
49 <img src="http://www.mamicode.com/images/star-off.png"/>
50 <img src="http://www.mamicode.com/images/star-off.png"/>
51 <img src="http://www.mamicode.com/images/star-off.png"/>
52 <img src="http://www.mamicode.com/images/star-off.png"/>
53 <img src="http://www.mamicode.com/images/star-off.png"/>
54 <img src="http://www.mamicode.com/images/star-off.png"/>
55 
56 总分为:<span id="span01"></span>
57 
58 </body>
59 </html>

 

购物车星星评分