星级评价功能实现

本例中的星级功能采用图片的方式来实现,包含半星、满星和不填充星。
代码部分

  • css部分
ul {
    display: flex;
}
ul, li {
    list-style: none;
}
.star {
    display: flex;
}			
.star li {
    display: block;
    width: 0.625rem;
    height: 0.625rem;
    margin-right: 0.125rem;
    font-size: 0;
}
.star li img {
    width: 100%;
    height: 100%;
}
  • html部分
<ul id="star1" class="star" data-score="2.9"></ul>
  • javascript部分
// 图片可以去iconfont图标库中下载对应的图片
// el表示选择器, score表示当前评分, fullStar表示星级评分满分分数(默认为5)
function stars({
    el,
    score,
    fullStar
}) {
    // 当前评分可以直接在js中设置,也可以在html中给data-core中给出,若两者都有,则以js中的分数为准
    var score = score || document.querySelector(el).getAttribute("data-score");
    var fullStar = fullStar || 5;
    var html = "";
    for (var i = 0; i < 5; i++) {
        if (i < parseInt(score)) {
            html += '<li><img src="imgs/fullstar.png" ></li>';
        } else if (score > i) {
            if (score - i >= 0.5) {
                html += '<li><img src="imgs/helfstar.png" ></li>';
            } else {
                html += '<li><img src="imgs/nonestar.png" ></li>';
            }
        } else {
            html += '<li><img src="imgs/nonestar.png" ></li>';
        }
}
document.querySelector(el).innerHTML = html;
}
stars({
    el: "#star1"
})

图片直接保存到本地即可

nonestar.png helfstar.png fullstar.png
posted @ 2019-04-02 17:01  luckiest  阅读(620)  评论(0)    收藏  举报