<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>js评价特效</title>
<style>
.wrapper{
width:300px;
margin:10px auto;
font:14px/1.5 arial;
}
/*tab*/
#star{overflow:hidden;}
#star li{
float:left;
width:20px;
height:20px;
margin:2px;
display:inline;
color:#999;
font:bold 18px arial;
cursor:pointer
}
#star .act{color:blue}
#star_word{
width:80px;
height:30px;
line-height:30px;
border:1px solid #ccc;
margin:10px;
text-align:center;
display:none
}
</style>
<script>
window.onload = function(){
var star = document.getElementById("star");
var star_li = star.getElementsByTagName("li");
var star_word = document.getElementById("star_word");
var result = document.getElementById("result");
var index = 0;
var len = star_li.length;
var word = ["很差", "差", "一般", "好", "很好"];
var clickIndex = -1;//声明一个变量并赋初值为-1,用来存放最后点击的li元素的索引值,由于li元素最小索引值是0,所以权且用-1表示从来没有点击过li元素。
console.log(clickIndex);
for(index=0; index<len; index++){
star_li[index].index = index;//将当前的元素的index属性索引值赋值。例如this.index为0,1,2,3等
star_li[index].onmouseover = function(){//onmouseover 事件会在鼠标指针移动到指定的元素上时发生。
star_word.style.display = "block";
star_word.innerHTML = word[this.index];//写入到star_word里面;this相当于star_li[index];
for(index=0; index<=this.index; index++){
star_li[index].className = "act";//利用它可以操作DOM元素的class属性,从而实现设置元素CSS样式等功能。此时的鼠标经过的star_li都变成红色
}
}
star_li[index].onmouseout = function(){//onmouseout 属性在鼠标指针移动到元素外时触发。
star_word.style.display = "none";
if (this.index <= clickIndex) {//如果小于clickIndex,就相当于没有任何操作
return;
} else {
for (var index = clickIndex + 1; index <= this.index; index++) {
star_li[index].className = "";//此时的鼠标经过后的star_li的颜色都消失;
}
}
}
star_li[index].onclick = function(){//onclick 事件会在对象被点击时发生。
result.innerHTML = (this.index + 1) + "分";
clickIndex = this.index;
for (index = 0; index < len; index++) {
star_li[index].className = "";
}
for (index = 0; index <= this.index; index++) {
star_li[index].className = "act";
}
}
}
}
</script>
</head>
<body>
<div class="wrapper">
打分结果:<span id="result"></span>
<ul id="star">
<li>★</li>
<li>★</li>
<li>★</li>
<li>★</li>
<li>★</li>
</ul>
<div id="star_word"></div>
</div>
</body>
</html>