已经有好多插件可以实现星星打分和显示,但只是根据分数来显示星星或半星时,只需用CSS实现会比较简洁不需要引用多于的JS。
HTML
<div>
<table>
<tr>
<td>评分:1.5</td>
<td>
<div class="rating-content" data-rating="1.5">
<span>★</span>
<span>★</span>
<span>★</span>
<span>★</span>
<span>★</span>
</div>
</td>
</tr>
</table>
</div>
CSS
.rating-content {
color: #ffa100;
}
.rating-content span {
display: inline-block;
position: relative;
}
.rating-content[data-rating="0.5"] span:nth-child(n+1),
.rating-content[data-rating="1.5"] span:nth-child(n+2),
.rating-content[data-rating="2.5"] span:nth-child(n+3),
.rating-content[data-rating="3.5"] span:nth-child(n+4),
.rating-content[data-rating="4.5"] span:last-child{
color: #FFF;
}
.rating-content[data-rating="0.5"] span:nth-child(n+1):before,
.rating-content[data-rating="1.5"] span:nth-child(n+2):before,
.rating-content[data-rating="2.5"] span:nth-child(n+3):before,
.rating-content[data-rating="3.5"] span:nth-child(n+4):before,
.rating-content[data-rating="4.5"] span:last-child:before{
content: "\2605";
display: block;
position: absolute;
width: 50%;
pointer-events: none;
overflow: hidden;
color: #ffa100;
}
.rating-content[data-rating="0.5"] span:nth-child(n+2),
.rating-content[data-rating="1.0"] span:nth-child(n+2),
.rating-content[data-rating="1.5"] span:nth-child(n+3),
.rating-content[data-rating="2.0"] span:nth-child(n+3),
.rating-content[data-rating="2.5"] span:nth-child(n+4),
.rating-content[data-rating="3.0"] span:nth-child(n+4),
.rating-content[data-rating="3.5"] span:nth-child(n+5),
.rating-content[data-rating="4.0"] span:nth-child(n+5){
display: none;
}
显示结果
想要显示不数量的星星时,只要修改data-rating
的设置值即可。
下方的链接可以直接动手调试
https://codepen.io/kou-kaisei/pen/OJOgwJE