D3 - Unable to set text color via css class

I use d3.js to create a javascript diagram and try to separate my style from behavior as much as possible. To do this, I'm trying to apply CSS classes using the .attr ('class', '...') method, rather than using the .style () method. For the most part, everything works fine. However, when I try to use the CSS class to set the stroke and fill in some text elements, it just doesn't work. The part that bothers me is that the same process of using .attr () to apply the css class worked fine for the columns of the graph, and that I have no problems with the text style as I want if I use the exact same attributes, but instead using the .style () method for each individual set. Even stranger, I can use the .attr () method to apply the transparency class via css without any problems. Is something 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 code that for some reason does not 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() }); 
+6
source share
2 answers

To set up multiple classes, use a single line containing all of them, not a chain of calls that will overwrite it.

That is, instead of

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

make

 .attr('class', 'white transparent') 
+6
source

Better use classified

 .classed('white', true); 

or even

 .classed('white transparent', true); 

This saves a lot of books in which the class was installed / removed later. Adding the data provided to the class is more complicated. See http://bl.ocks.org/clemens-tolboom/7231676

+17
source

Source: https://habr.com/ru/post/947123/


All Articles