1

我将获得 4.3 的平均评分,我需要构建逻辑以在星形图标中显示 4.3 的平均评分(4 个全星,第 5 个星为部分填充)。最大评分数为 5。我通过引用 stackoverflow 示例创建了 jsfiddle,并且我的草稿小提琴中没有得到部分星,结果我得到了整颗星。我的 JSFiddle 截图

JSFiddle 链接https ://goo.gl/sz1YIJ 请建议。

4

2 回答 2

7

更新:

针对评论,您可以将数百个有用的 unicode 符号复制并粘贴到您的代码中,例如 ▲ ▼ ★ 。这些比图标图像效果更好,因为您可以使用 css 设置颜色和大小。要查找符号,例如下面标题中的人,请尝试搜索unicode-table

一个简单的解决方案


似乎这可以通过一点点 css 和 Javascript 非常简单地完成。

这里我们有一个 5 星的 div。我们调整宽度以显示或隐藏星星。关键是使用溢出隐藏和内联块样式,然后在初始化时捕获 clientWidth。这比使用 em 单位或其他方法更可靠。

显然你可以进一步增强它,但我想展示所需的最少代码。

运行代码段并输入从 0 到 5 的任何小数星值。

var cw = window.rating1.clientWidth; // save original 100% pixel width

function rating( stars ) {
  window.rating1.style.width = Math.round(cw * (stars / 5)) + 'px';
}

rating(4.3);
.rating {
  font-size: 48px;
  color: orange;
  display: inline-block;
  overflow: hidden;
}
.rating::before { 
  content: "★★★★★" 
}
Enter a star rating 0-5: <input onkeyup="rating(this.value)" value="4.3"> 
<p>
<div id="rating1" class="rating"></div>

于 2016-02-25T00:29:25.463 回答
3

我写了一个函数来满足你的需要。它只是设置部分图标的宽度,隐藏溢出。

function setFractionalRating(container, value) {
    var floor = Math.floor(value),
        ceil = Math.ceil(value),
        star = container.children[floor],
        slice = Array.prototype.slice,
        children = slice.call(container.children),
        visible = slice.call(children, 0, ceil),
        hidden = slice.call(children, ceil),
        size,
        width,
        portion;
  
    visible.forEach(function(star) {
        star.style.visibility = 'visible';
      	star.style.width = '';
    });
    hidden.forEach(function(star) {
        star.style.visibility = 'hidden';
        star.style.width = '';
    });

    size = star && star.getBoundingClientRect();
    width = size && size.width;
    portion = value - floor;

    if (star && portion !== 0)
        star.style.width = (width * portion) + 'px';
}


// Test:
var check = 1,
    debug = document.querySelector('.debug');
debug.appendChild(document.createTextNode(''));
setInterval(function(rating) {
    debug.firstChild.nodeValue = check.toFixed(1);
    setFractionalRating(rating, check);
    if ((check += 0.1) >= 5)
        check = 0.1;
}, 200, document.querySelector('.rating'));
.rating > i {
  display: inline-block;
  overflow: hidden;
}
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="rating">
  <i class="glyphicon glyphicon-star"></i>
  <i class="glyphicon glyphicon-star"></i>
  <i class="glyphicon glyphicon-star"></i>
  <i class="glyphicon glyphicon-star"></i>
  <i class="glyphicon glyphicon-star"></i>
</div>
<div class="debug">
</div>
</div>

于 2016-02-24T23:06:51.117 回答