代码之家  ›  专栏  ›  技术社区  ›  SavageBooBoo

d3如何根据值更改文本颜色(如果其他)

  •  0
  • SavageBooBoo  · 技术社区  · 7 年前

    我有一个数据集,基于我想要打印的值,“警告:乔今天看了14个猫视频”,黑色或红色。如果值大于10,则显示为红色。 在使用d3或html格式时如何做到这一点??

    var dataset = [14, 5, 26, 23, 9];
    d3.select("body").selectAll("p")
        .data(dataset)
        .enter()
        .append("p")
        .style('fill', 'darkOrange')
        .text(function(d, i){
            for (i=0; i<5; i++)
            {
                result = "Warning: Joe watched " + d + " cat videos today";
            }
            return result;
        });
    

    需要看起来像这样

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  2
  •   Nirali    7 年前

    看看这个

    添加样式属性以根据数组的值更改文本的颜色

    .style("color", function(d, i) {
          return d > 10 ? "#ff0000" : "#000";
        })
    

    并在中添加if else。text(函数(d,i){}根据答案中的条件更改文本

    var dataset = [14, 5, 26, 23, 9];
    d3.select("body").selectAll("p")
        .data(dataset)
        .enter()
        .append("p")
        .style('fill', 'darkOrange')
        .style("color", function(d, i) {
          return d > 10 ? "#ff0000" : "#000";
        })
        .text(function(d, i){
            for (i=0; i<dataset.length; i++)
            {
                if(d > 10)
                {
                  result = "Warning: Joe watched " + d + " cat videos today";
                 }
                 else
                 {
                  result = "Joe watched " + d + " cat videos today";
                 }
            }
            return result;
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://d3js.org/d3.v5.min.js"></script>