先来个大略单纯版的:
html代码
<div class="box">
<div class="bottom star-wrap">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<div class="mask star-wrap" style="width:95%;">
<!-- 这里须要外加个容器设置足够大的宽度,防止宽度不足,内容往下掉 -->
<div style="width:300px;">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
</div>
css代码
.box {
position: relative;
display: inline-block;
}
.star-wrap span {
float: left;
width: 16px;
height: 16px;
}
.star-wrap span:not(:last-child) {
margin-right: 4px;
}
.bottom span {
background: url(./assets/img/star.png) 0 0 no-repeat;
}
.mask span {
background: url(./assets/img/star_1.png) 0 0 no-repeat;
}
.mask {
position: absolute;
left: 0;
top: 0;
overflow: hidden;
}
实在便是两层叠加,须要把稳的是mask里须要增加个容器设置足够大的宽度,防止宽度不足,内容往下掉,效果如下

这里创造个问题,95%末了一个star的宽度该当占一半,但是现在只有1/3,这是由于星星之间有5像素的间距,以是还得打算星星所占的实际百分比
打算公式:
首先打算实际星星所占百分比的宽度:6 10 95%
打算间距宽度:Math.floor(196(总间隔) 95% / (16(每个星星的宽度) + 4(空格间距))) 4
两个间隔相加就得到了实际间隔了
js代码
let w = 16 10 percent + Math.floor(196 percent / (16 + 4)) 4
document.getElementById('mask').style.width = (w / 196).toFixed(2) 100 + '%';
完全代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>星级评分</title>
<style>
.box {
position: relative;
display: inline-block;
}
.star-wrap span {
float: left;
width: 16px;
height: 16px;
}
.star-wrap span:not(:last-child) {
margin-right: 4px;
}
.bottom span {
background: url(./assets/img/star.png) 0 0 no-repeat;
}
.mask span {
background: url(./assets/img/star_1.png) 0 0 no-repeat;
}
.mask {
position: absolute;
left: 0;
top: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div class="box">
<div class="bottom star-wrap">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<div class="mask star-wrap" id="mask">
<!-- 这里须要外加个容器设置足够大的宽度,防止宽度不足,内容往下掉 -->
<div style="width:300px;">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
</div>
<script>
function calcWidth(percent) {
let w = 16 10 percent + Math.floor(196 percent / (16 + 4)) 4
document.getElementById('mask').style.width = (w / 196).toFixed(2) 100 + '%';
}
calcWidth(0.95);
</script>
</body>
</html>