半圈渐变js

时间:2017-01-07 19:28:32

标签: javascript jquery html css

如何在圆圈中获得渐变效果?我有这样一个initial code

HTML:

 <div class="progresss">
   <div class="barOverflow">
     <div class="bar"></div>
   </div>
   <span>10</span>%
 </div>

 <div class="progresss">
   <div class="barOverflow">
     <div class="bar"></div>
   </div>
   <span>75</span>%
</div>

SCSS:

.progresss{
    position: relative;
    margin: 4px;
    float:left;
    text-align: center;
}
.barOverflow{ /* Wraps the rotating .bar */
    position: relative;
    //overflow: hidden; /* Comment this line to understand the trick */
    width: 145px; height: 45px; /* Half circle (overflow) */
    margin-bottom: -14px; /* bring the numbers up */

    &:after {
        content: '';
        position: relative;
        display: block;
        top: -75px;
        width: 145px;
        height: 90px;
        background-color: #f3f5f6;
    }
}
    .bar{
    position: relative;
    top: 0; left: 0;
    width: 145px; height: 145px; /* full circle! */
    border-radius: 50%;
    box-sizing: border-box;
    border: 27px solid red;       /* half red, */
    border-bottom-color: green;  /* half green */
    border-right-color: green;

}

JS:

$(".progresss").each(function(){

  var $bar = $(this).find(".bar");
  var $val = $(this).find("span");
  var perc = parseInt( $val.text(), 10);

  $({p:0}).animate({p:perc}, {
    duration: 3000,
    easing: "swing",
    step: function(p) {
      $bar.css({
        transform: "rotate("+ (45+(p*1.8)) +"deg)", // 100%=180° so: ° = % * 1.8
        // 45 is to add the needed rotation to have the green borders at the     bottom
      });
      $val.text(p|0);
    }
  });
});

我想要的是:

enter image description here

1 个答案:

答案 0 :(得分:0)

我在当天做了类似的事情,当我发现使用CSS border-image property实现渐变边框的唯一方法是(我猜仍然是)时,我提出了完全不同的方法:

  1. 创建3个嵌套的div元素:

    • wrapper,我们需要隐藏溢出,
    • out,这是一个渐变background颜色的那个 - 就是我们要旋转的那个,
    • in,这是显示增长百分比数字的内圈
  2. 首先在wrapper内添加一些元素来保存百分比数字并使用position: absolute,将其放在父级的中间:我们不会在in中显示百分比元素,因为它与out一个旋转,并且创建另一个元素比同步两个圆的旋转更容易。

  3. wrapper成为一个圆圈并隐藏它的溢出 - 它有助于 4。:

  4. 赋予out元素渐变背景,下半部分为绿色,上半部分为透明 - 由于它的父级溢出而形状为圆形。

  5. 其余的只是数学:你可以在my fiddle 中查看。

  6. 这不是完美的解决方案,如果您使用百分比widthheight,我不介意发布它。但是,当我看到固定的(px)尺寸时,我认为你也可以使用我的方法。

    根据您的需要调整它 - 梯度和尺寸,如果您无法定位整个事物,只需使用wrapper元素,孩子将“跟随”。

相关问题