D3——根据数据画图
为DOM元素添加class
.attr("class", "bar") //为元素添加class属性,<div class="bar"></div> .classed("bar", true) //添加class "bar" .classed("bar", false) //删除class "bar"
Drawing Bars:
var dataset = [ 5, 10, 15, 20, 25 ]; d3.select("body").selectAll("div") .data(dataset) .enter() .append("div") .attr("class", "bar"); //css div.bar { display: inline-block; width: 20px; height: 75px; /* We'll override height later */ background-color: teal; }
Setting Styles
.style("height", function(d) { return d + "px"; });
优化一下
.style("height", function(d) { var barHeight = d * 5; //Scale up by factor of 5 return barHeight + "px"; }); //并设margin-right:2px;