不废话,直接上代码!
html:
<div id="wrap">
<div id="box">
<span class="title">星级评分:</span>
<ul class="list">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div id="txt">请给出你心中评分</div>
</div>
</div>
css: 这里的星星图片自己找一下哦!大概长这样
body{font-family: "Microsoft YaHei",serif;user-select:none;}
body,dl,dd,p,h1,h2,h3,h4,h5,h6{margin:0;}
ol,ul,li{margin:0;padding:0;list-style:none;}
img{border:none;}
#box{
display: flex;
width: 500px;
height: 100px;
margin: 100px auto;
}
.title{
color: red;
line-height: 100px;
}
.list{
display: flex;
width: 100px;
height: 20px;
margin: 0 10px;
padding-top: 40px;
}
.list li{
width: 20px;
height: 20px;
background-image: url("./imgs/star.png");
background-position: 0 0;
}
.list li.show{
background-position: 0 100%;
}
#txt{
width: 50%;
height: 100%;
line-height: 100px;
text-align: center;
border: 1px solid #ccc;
}
js:
let oList = document.querySelector(".list"),
oLi = document.querySelectorAll(".list li"),
oTxt = document.getElementById("txt"),
rates = ["请给出你心中评分","残次","合格","中等","良好","优秀"],
len = oLi.length,
index = -1;
for(let i = 0;i < len; i++){
oLi[i].onmouseenter = function(){ //鼠标移入
for(let j = 0; j < len; j++){
oLi[j].className = j <= i?"show":"";
}
oTxt.innerHTML = rates[i+1];
// for(let j = 0; j <= i; j++){
// oLi[j].className = "show";
// }
// for(let j = i+1; j < len; j++){
// oLi[j].className = "";
// }
}
oLi[i].onclick = function(){ //鼠标点击,确定当前评分
index = i;
}
}
oList.onmouseleave = function() { //鼠标离开
for(let i = 0; i < len; i++){
oLi[i].className = i <= index?"show":"";
}
oTxt.innerHTML = rates[index+1];
}