<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#ul1{
width: 200px;
height: 28px;
padding: 0;
margin: 0;
list-style:none;
}
#ul1 li{
width: 27px;
height: 28px;
float: left;
background: url(../img/star.gif) no-repeat 0 0;
}
</style>
</head>
<body>
<ul id="ul1">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div id="box"></div>
<script>
/*
分析:
所有的li
移入事件
if(是否点击过){
if(移入的下标 >= 点击的下标){
所有星星变为灰色
0~当前移入的下标变为金色
}
}else{
所有星星变为灰色
0~当前移入的下标变为金色
}
移出事件
if(是否点击过){
if(移入的下标 >= 点击的下标){
点击的下标之后的星星变为灰色
}
}else{
所有星星变为灰色
}
点击事件
显示评价内容
所有星星变为灰色
0~当点击的下标变为金色
是否点击过 = true
点击的下标 = 下标
*/
class Star{
constructor(){
//属性
//获取所有的li
this.li = document.querySelectorAll('#ul1>li');
//获取评价盒子
this.div = document.querySelector('#box');
//准备数组,存放评价内容
this.arr = ['差','一般','好','很好','非常好'];
//是否点击过
this.is_click = false;
//记录点击下标
this.click_index = null; //默认没有点击,没有下标
//添加事件
this.addEvent();
}
addEvent(){
//遍历li添加事件
for(let i = 0,len = this.li.length;i < len;i ++){
//移入事件
this.li[i].onmouseover = () => {
if(this.is_click){
if(i >= this.click_index){
// 所有星星变为灰色
for(let j = 0;j < len;j ++){
this.li[j].style.background = 'url(../img/star.gif) no-repeat 0 0';
}
// 0~当前移入的下标变为金色
for(let k = 0;k <= i;k ++){
this.li[k].style.background = 'url(../img/star.gif) no-repeat 0 -28px';
}
}
}else{
// 所有星星变为灰色
for(let j = 0;j < len;j ++){
this.li[j].style.background = 'url(../img/star.gif) no-repeat 0 0';
}
// 0~当前移入的下标变为金色
for(let k = 0;k <= i;k ++){
this.li[k].style.background = 'url(../img/star.gif) no-repeat 0 -28px';
}
}
}
// 移出事件
this.li[i].onmouseout = () => {
if(this.is_click){
if(i >= this.click_index){
// 点击的下标之后的星星变为灰色
for(let j = this.click_index + 1;j < len;j ++){
this.li[j].style.background = 'url(../img/star.gif) no-repeat 0 0';
}
}
}else{
// 所有星星变为灰色
for(let j = 0;j < len;j ++){
this.li[j].style.background = 'url(../img/star.gif) no-repeat 0 0';
}
}
}
//点击事件
this.li[i].onclick = () => {
// 显示评价内容
this.div.innerText = this.arr[i];
// 所有星星变为灰色
for(let j = 0;j < len;j ++){
this.li[j].style.background = 'url(../img/star.gif) no-repeat 0 0';
}
//0~当点击的下标变为金色
for(let k = 0;k <= i;k ++){
this.li[k].style.background = 'url(../img/star.gif) no-repeat 0 -28px';
}
// 是否点击过 = true
this.is_click = true;
// 点击的下标 = 下标
this.click_index = i;
}
}
}
}
new Star();
</script>
</body>
</html>
所需图片自行下载【资源 start】