Using CSS Values ​​in a D3 Transition

I would like to make the transition d3 to the style defined in CSS. I can successfully move on to a style value that I explicitly apply in the code. But I would like the animation target values ​​to be defined in the stylesheet.

Here is an example of a red div that goes blue:

<html> <head> <script src="http://d3js.org/d3.v3.js"></script> <style> div { background: red } </style> </head> <body> <div>Hello There</div> <script> d3.select('body div') .transition() .duration(5000) .style("background", "cornflowerblue"); </script> </body> </html> 

And here is my (incorrect) attempt to "save" these values ​​in CSS:

 <html> <head> <script src="http://d3js.org/d3.v3.js"></script> <style> div { background: red } div.myDiv { background: cornflowerblue } </style> </head> <body> <div>Hello There</div> <script> d3.select('body div') .transition() .duration(5000) .attr("class", "myDiv"); </script> </body> </html> 

The former animates the background from red to blue. The latter jumps from red to blue (by the background value defined in CSS).

I think I understand why this is not working. Can I animate a CSS-style value set in d3 and how do I do this?

+6
source share
1 answer

selection.style will return the style created by the browser (from external CSS) if you do not pass it a value. To get the background color, for example:

 var bg = d3.select('div').style('background-color'); 

You can add some hidden elements with the classes needed to get colors from CSS if you don't want to hardcode them in your JS. Sort of

 var one = d3.select('body').append('div').class('my-first-color'); var two = d3.select('body').append('div').class('my-second-color'); 

Then one and two will have the desired styles. So.

 var fake_div = d3.select('body').append('div').attr('class', 'some_class').style('display', 'none'), new_color = fake_div.style('background-color'); // We don't need this any more fake_div.remove(); // Now we have an explicit value, effectively fetched from our CSS d3.select('div').style('background-color', new_color); 

Here is the fiddle .

+8
source

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


All Articles