2016-08-22 58 views
3

这里是我写的代码 -D3js包括多个样式

<!DOCTYPE html> 
<meta charset="utf-8"> 
<html> 
<style> 
    div.bar{ 
     display: inline-block; 
     width: 20px; 
     height: 75px; 
     background-color: blue; 
     margin-right: 5px; 
    } 
</style> 
<head> 
    <title> Simplebar - Out Dataset </title> 
    <script src="https://d3js.org/d3.v4.js"></script> 
</head> 
<body> 
    <script type="text/javascript"> 
    d3.csv("officedata.csv", function(data){ 
      console.log(data); 

    d3.select("body") 
     .selectAll("div") 
     .data(data) 
     .enter() 
     .append("div") 
     .attr("class", "bar") 
     .style("height", function(d){ 
      var bheight = d.age*5; //scales the bar height 10 times 
      return bheight + "px"; 
      }) 
     .style("color", function(d){ 
      if(d.age > 30) { return "red"; } 
      else { return "blue"; }) 
    }); 
    </script> 
</body> 
</html> 

,这里是CSV文件 -

name,age 
pragyan,23 
rashmi,26 
tumon,40 
debajit,50 
dhiraj,19 

我想给条件的颜色应为红色如果年龄在30岁以上。我已经尝试了一个单独的代码中的颜色部分,它正在工作,但是当我在这里尝试它时,它不起作用。去除颜色部分,高度工作得很好。

如何添加两个样式属性?请帮忙。

+1

尝试 “背景颜色” 而不是 “颜色”。 –

回答

1

1)而不是颜色使用背景颜色。

2)通过设置d.age = + d.age使年龄成为数字。 目前其字符串如此d.age > 30将无法​​按预期工作。

 .style("background-color", function(d) { 
      d.age = +d.age; 
      if (d.age > 30) { 
       return "red"; 
      } else { 
       return "blue"; 
      } 
     }); 

工作代码here

+0

非常感谢。这工作。好极了! –

+1

新问题和答案中的Stackoverflow。做到了。 再次感谢西里尔。帮了我很多。 :) –