龙空技术网

css实现小数点星级评分

onezero 121

前言:

目前小伙伴们对“css评分”大体比较注意,你们都需要学习一些“css评分”的相关内容。那么小编同时在网摘上网罗了一些有关“css评分””的相关内容,希望咱们能喜欢,看官们快快来学习一下吧!

最近做项目有个类似星级评分的功能,不过是小数点的,刚开始想的是用css的一些高级属性,但是并没有达到想要的效果,最终还是用普通css和js实现了个。

先来个简易版的:

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>

标签: #css评分