我试图显示一个百分比值,圆圈试图用代码创建下面的图像。我将从HTML中获取百分比值。我只是不知道如何用css部分地给圆上色。
javascript - CSS部分颜色百分比值-LMLPHP

<div class="meter" data-attr="50%">
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>

.meter {
  span {
    display: inline-block;
    width: 25px;
    height: 25px;
    border-radius: 50%;
    border: 1px solid red;
  }
}

<script>
  var circlePrecent = 50%;
</script>

https://jsfiddle.net/j8of7yag/

最佳答案

使用基本的背景色,并用线性渐变覆盖。使用js中的backgroundSize控制线性渐变的大小:

  background: #AB9E95 linear-gradient(to right, #9F1F63 0%, #9F1F63 100%) no-repeat;

工作演示:
colorCircles('65%');

setTimeout(function() {
  colorCircles('37%');
}, 1000);

function colorCircles(percentage) {
  var value = parseInt(percentage, 10);

  var circles = Array.from(document.querySelectorAll('.meter > span'));

  var fullCircles = Math.floor(value / 20);

  var partialCircle = (value % 20) / 20 * 100;

  circles.forEach(function(circle, index) {
    var backgroundSize = '0% 100%';

    if (index < fullCircles) {
      backgroundSize = '100% 100%';
    } else if (index === fullCircles) {
      backgroundSize = partialCircle + '% 100%';
    }

    circle.style.backgroundSize = backgroundSize;
  })
}

.meter {
  display: inline-block;
  box-sizing: border-box;
}
span {
  display: inline-block;
  left: 0;
  width: 25px;
  height: 25px;
  border-radius: 50%;
  border: 1px solid red;
  background: #AB9E95 linear-gradient(to right, #9F1F63 0%, #9F1F63 100%) no-repeat;
  transition: background-size 0.3s;
}

<div class="meter">
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>

09-25 17:11