场景:有些需求会要求用原生去实现点亮星星评分的效果,下面做了一个简单的demo,效果如下:
1.html部分
<div class="box">
<img src="./images/start-1.png" alt="">
<img src="./images/start-1.png" alt="">
<img src="./images/start-1.png" alt="">
<img src="./images/start-1.png" alt="">
<img src="./images/start-1.png" alt="">
<div class="text"><span></span>分</div>
</div>
2.css部分
.box {
width: 600px;
height: 100px;
border: 2px solid #9acd32;
margin: 200px auto;
display: flex;
justify-content: center;
position: relative;
}
.box img {
width: 100px;
height: 100px;
}
.box .text {
font-size: 20px;
font-weight: 600;
color: #ccc;
position: absolute;
right: -80px;
top: 50%;
transform: translateY(-50%);
}
.box .text span {
color: #9acd32;
}
3.js部分
var num = 2;//默认点亮个数
$item = $('.box').find('img');//获取的所有img
//点亮星星函数
var dianLiang = function (num) {
$item.each(function (index) { //遍历所有img,即所有星星
if (index < num) {
$(this).attr('src', './images/start-2.png') //点亮
} else {
$(this).attr('src', './images/start-1.png') //未点亮
}
})
}
//初始化,默认点亮2颗
dianLiang(num)
// 绑定事件
$item.on('mouseover', function () {
let index=$(this).index() * 1 + 1
dianLiang(index)
$('.text span').text(index)
}).on('click', function () {
let index=$(this).index() * 1 + 1
dianLiang(index);
$('.text span').text(index)
num = index
})
$('.box').on('mouseout', function () {
dianLiang(num)
})