Javascript - 创建褪色堆积条形图

时间:2017-12-10 10:44:49

标签: javascript jquery css

我遇到以下问题:如何创建一个只能容纳3个变量的堆积条形图。 (x, y, z) x + y + z = 100%

重要的是如何使条形的x y和y z之间的颜色边缘变淡,如下图所示? (可以使用任何流行的图书馆)

enter image description here

2 个答案:

答案 0 :(得分:1)

我使用CSS制作了静态解决方案: 你只需要"替换"使用javascript使用适当值的%unities(这不会是一个大问题)。 解决方案:首先:没有可能在纯css中交叉颜色。所以我添加到条形图上的绝对定位div,背景颜色包含透明度。 HTML:

<div class="bar">
  <div class="agree">
    20%
  </div>
  <div class="seperator part1">

  </div>
  <div class="independants">
     30%
  </div>
  <div class="seperator part2">

  </div>
  <div class="disagree">
     50%
  </div>
</div>

CSS:

.bar {
  display: flex;
  width: 100%;
  border: 1px solid #000;
  border-radius: 3px;
}

.bar > div {
  height: 20px;
  color: #fff;
  text-align: center;
}
.agree {
  flex: 1 0 20%;
  background: green;
}

.independants {
  flex: 1 0 30%;
  background: orange;
}
.disagree {
  flex: 1 0 50%;
  background: red;
}

.seperator {
  position: absolute;
  width: 5%;
  z-index: 20;
}
.part1 {
  left: 16%;
  background: linear-gradient(to right, rgba(122,188,255,0) 0%,rgba(249,186,97,0.44) 44%,rgba(237,176,64,1) 100%);
}
.part2 {
  left: 50%;
  background: linear-gradient(to right, rgba(255,164,28,1) 0%,rgba(249,186,97,0.56) 44%,rgba(237,176,64,0) 100%);
}

在这里查看小提琴:https://jsfiddle.net/taxostd0/5/

答案 1 :(得分:1)

您可以在css中使用具有四个百分比位置的单个线性渐变来实现所需的结果。您不需要指定0%和100%颜色,但是您需要在两侧开始和结束几个百分点的渐变,否则您将获得难以更改的颜色。这是一个可以帮助您集中标签的功能,但它不处理验证或边缘情况。

function updateGradientBar(agree, depends, disagree) {

  let
  	padding = 3,
    agreeFadeStart = agree - padding,
    dependsFadeStart = agree + padding,
    dependsFadeEnd = agree + depends - padding,
    disagreeFadeStart = agree + depends + padding,

    labelAgree = $('#gradient-bar .label.agree'),
    agreeLabelPosition = agree / 2,

    labelDepends = $('#gradient-bar .label.depends'),
    dependsLabelPosition = agree + (depends / 2),

    labelDisagree = $('#gradient-bar .label.disagree'),
    disgreeLabelPosition = agree + depends + (disagree / 2);


  $('#gradient-bar').css(
    'background',
    'linear-gradient(to right, green ' + agreeFadeStart + '%,' + 'orange ' + dependsFadeStart + '%, orange ' + dependsFadeEnd + '%,' + 'red ' + disagreeFadeStart + '%)');


  labelAgree.css('left', agreeLabelPosition + '%').text(agree + '%');
  labelDepends.css('left', dependsLabelPosition + '%').text(depends + '%');
  labelDisagree.css('left', disgreeLabelPosition + '%').text(disagree + '%');

}

updateGradientBar(35, 40, 25);
#gradient-bar {
  height: 20px;
  border-radius: 4px;
  background: blue;
  position: relative;
}

#gradient-bar .label {
  color: white;
  font-weight: bold;
  position: absolute;
  top: 50%;
  transform: translatex(-50%) translateY(-50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="gradient-bar">
  <div class="label agree"></div>
  <div class="label depends"></div>
  <div class="label disagree"></div>
</div>