css径向进度条增量为1%

时间:2013-10-12 01:46:34

标签: css sass

我在codepen上找到了一个简洁的纯CSS旋钮,但它只产生5的倍数百分比类(例如5%,10%,20%等)。

http://codepen.io/brewing/pen/Imxpc

$barColor: tomato
$overlayColor: #fffde8
$backColor: #2f3439

$step: 5 // step of % for created classes

$loops: round(100 / $step)
$increment: round(360 / $loops)
$half: round($loops / 2)
@for $i from 0 through $loops
  .progress-#{$i*$step}
    @if $i < $half
      $nextdeg: 90deg + ( $increment * $i )
      background-image: linear-gradient(90deg, $backColor 50%, transparent 50%, transparent), linear-gradient($nextdeg, $barColor 50%, $backColor 50%, $backColor)
    @else
      $nextdeg: -90deg + ( $increment * ( $i - $half ) )
      background-image: linear-gradient($nextdeg, $barColor 50%, transparent 50%, transparent), linear-gradient(270deg, $barColor 50%, $backColor 50%, $backColor)

生成的最后3个类看起来像这样:

.progress-90 {
  background-image: linear-gradient(54deg, tomato 50%, transparent 50%, transparent), linear-gradient(270deg, tomato 50%, #2f3439 50%, #2f3439);
}

.progress-95 {
  background-image: linear-gradient(72deg, tomato 50%, transparent 50%, transparent), linear-gradient(270deg, tomato 50%, #2f3439 50%, #2f3439);
}

.progress-100 {
  background-image: linear-gradient(90deg, tomato 50%, transparent 50%, transparent), linear-gradient(270deg, tomato 50%, #2f3439 50%, #2f3439);
}

但是当我尝试更改它以生成从0到100的所有百分比的类时,类最终会出现第一个渐变的错误角度:

.progress-90 {
  background-image: linear-gradient(70deg, tomato 50%, transparent 50%, transparent), linear-gradient(270deg, tomato 50%, #2f3439 50%, #2f3439);
}

.progress-95 {
  background-image: linear-gradient(90deg, tomato 50%, transparent 50%, transparent), linear-gradient(270deg, tomato 50%, #2f3439 50%, #2f3439);
}

.progress-100 {
  background-image: linear-gradient(110deg, tomato 50%, transparent 50%, transparent), linear-gradient(270deg, tomato 50%, #2f3439 50%, #2f3439);
}

1 个答案:

答案 0 :(得分:1)

问题出现是因为它使用整数运算。

当你想要1%步时,变成$ increment = 3.6度。它会四舍五入为4,这就会导致问题。

更改微积分,使其不使用增量,而是使用原始微积分:

@if $i < $half
    $nextdeg: 90deg + ( 360 * $i / $loops )
    background-image: linear-gradient(90deg, $backColor 50%, transparent 50%, transparent), linear-gradient($nextdeg, $barColor 50%, $backColor 50%, $backColor)
@else
    $nextdeg: -90deg + ( 360 * ( $i - $half ) / $loops )
    background-image: linear-gradient($nextdeg, $barColor 50%, transparent 50%, transparent), linear-gradient(270deg, $barColor 50%, $backColor 50%, $backColor)

请注意,唯一的变化是替换公式的$ increment来计算它

demo