![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ffb725d9961af4e06a334238be8be9c5.png)
<style>
*{
margin: 0;
padding: 0;
}
ul li{
list-style: none;
}
ul{
margin: 100px 0 0 300px;
display: inline-block;
}
.star li{
width: 40px;
height: 40px;
background: url("../assents/details_icon_collect@2x.png");
float: left;
}
.star li.active{
width: 40px;
height: 40px;
background: url("../assents/details_icon_collect_1@2x.png");
}
</style>
<ul class="star">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<script>
var li = document.querySelectorAll('.star li')
var star = document.querySelector('.star')
var curIndex = null
//1,
for(var i = 0;i<li.length;i++){
li[i].setAttribute('data-idx',i)
//知道经过的元素
li[i].onmouseenter = function () {
//获取下标
var idx = this.getAttribute('data-idx')
show(idx)
}
li[i].onclick = function () {
var idx = this.getAttribute('data-idx')
curIndex = idx
console.log(idx)
show(curIndex)
}
}
//2,
function show(num) {
//首先让他们都暂时不亮
for(var j = 0;j<li.length;j++){
li[j].className = ''
}
//移到哪里亮到哪儿
for(var i = 0;i<=num;i++){
li[i].className = 'active'
}
}
//3,
//鼠标离开时判断有没有点击
star.onmouseleave = function () {
if(curIndex == null){
for(var j = 0;j<li.length;j++){
li[j].className = ''
}
}else{
for(var i = 0;i<li.length;i++){
li[i].className = ''
}
for(var j = 0;j<=curIndex;j++){
li[j].className = 'active'
}
}
}
star.onmouseenter =function () {
for(var j = 0;j<li.length;j++){
li[j].className = ''
if(curIndex !== null){
for(var k = 0;k<=curIndex;k++){
li[k].className = 'active'
}
}
}
}
</script>