7

I am using d3.js to create a javascript chart, and am trying to separate my styling from behavior as much as possible. To do this, I am trying to apply CSS classes using the .attr('class','...') method rather than using the .style() method. For the most part everything works just fine. However, when I try to apply a CSS class to set the stroke and fill of some text elements, it just doesn't work. The part that has me confused is the fact that the same process of using .attr() to apply a css class worked fine for the bars of the graph, and that I have no issue styling the text how I want if I use the exact same attributes, but instead with the .style() method to set each individually. Even more bizarre, I can use the .attr() method to apply a transparency class via css without any issue. Is there something I am missing here?

These are the css classes in question:

    .black {
    fill: rgb(41,41,41);
    stroke: rgb(41,41,41);
 }

 .red {
    fill: rgb(238,77,77);
    stroke: rgb(238,77,77);
    color: rgb(238,77,77);
 }

 .blue {
    fill: rgb(76,179,230);
    stroke: rgb(76,179,230);
 }

 .white {
    fill: rgb(255,255,255);
    stroke: rgb(255,255,255);
 }

and this is the code that, for some reason doesn't work:

 var severityText = chart.selectAll(".severity")
        .data(array)
        .enter().append("text")
        .attr("x", function (d, i) { return x(i) + barWidth / 2 - (5.0/8)*barNumberSize; })
        .attr("y", function (d, i) { return bubbleY(maxBubbleValue - d['severity']) - bubbleRadius / 2 - bubbleNumberSize*(1.0/4) })
        .style("font-size", bubbleNumberSize.toString() + "px")
        //this line isn't doing its job
        .attr('class','white')
        .attr('class','transparent')
        .text(function (d, i) { return d['severity'].toString() });

while this code does:

var severityText = chart.selectAll(".severity")
        .data(array)
        .enter().append("text")
        .attr("x", function (d, i) { return x(i) + barWidth / 2 - (5.0/8)*barNumberSize; })
        .attr("y", function (d, i) { return bubbleY(maxBubbleValue - d['severity']) - bubbleRadius / 2 - bubbleNumberSize*(1.0/4) })
        .style("font-size", bubbleNumberSize.toString() + "px")
        //works fine when written in this format.....why?
        .style('fill',white)
        .style('stroke',white)
        .attr('class','transparent')
        .text(function (d, i) { return d['severity'].toString() });
4

2 回答 2

21

最好使用分类

.classed('white', true);

甚至

.classed('white transparent', true);

这可以节省大量的记录,以便稍后设置/删除什么类。添加数据提供的类名更加困难。参见http://bl.ocks.org/clemens-tolboom/7231676

于 2013-11-03T16:56:10.223 回答
6

要设置多个类,请使用包含所有类的单个字符串,而不是链接调用,这将覆盖它。

也就是说,而不是

.attr('class','white')
.attr('class','transparent')

.attr('class', 'white transparent')
于 2013-06-12T15:43:00.337 回答