最近做项目有个类似星级评分的功能,不过是小数点的,刚开始想的是用css的一些高级属性,但是并没有达到想要的效果,最终还是用普通css和js实现了个。
先来个简易版的:
html代码
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 + '%';
完整代码:
星级评分.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;
}
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);