Using CSS Values in a D3 Transition

2020-07-11 07:25发布

问题:

I'd like to make d3 transition to a style defined in CSS. I can successfully transition to a style value which I explicitly apply in code. But, I'd like the target values of the animation to be defined in a style sheet.

Here's an example of a red div which transitions to a blue one:

   <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's a my (incorrect) attempt at "storing" 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 (no tweening is applied to background value defined in the CSS).

I think I understand why it doesn't work. Can I animate to a set of values in a CSS style in d3, and how would I do it?

回答1:

selection.style will return the browser generated style (from external CSS) if you don't pass a value to it. To get the background color for example:

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

You could append some hidden elements with the classes you need to fetch the colors from CSS if you don't want to hardcode them in your JS. Something like

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 would have the styles you need. 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's a Fiddle.