简体   繁体   中英

Clicks, toggles and transitions in D3

I was looking at another q on here ( d3 javascript alternate colors on click ) and was wondering how it would be possible to bring in a transition to the change.

I've re-written the code slightly so that the toggle function changes the location of the circle rather than the colour.

var SVG = d3.select("body")
    .append("svg")
    .attr("width", 300)
    .attr("height", 300);    

var togglex = (function(){
var currentx = 50;

return function(){
    currentx = currentx == 50 ? 200 : 50;
    d3.select(this).attr("cx", currentx);
}
})();



SVG.append("circle")
    .style("stroke", "gray")
    .style("fill", "white")
    .attr("r", 20)
    .attr("cx", 50)
    .attr("cy", 50)
    .on("click", togglex);

So the togglex function moves the circle around when it's clicked. I've tried to put a transition in both before and after the .on("click", toggle) but it doesn't work. (I can kind of understand why it doesn't, it's a function, not a position on the screen). I've also tried building the transition into the function itself but that didn't work either, at least not how I did it. (Again, I can see why that wouldn't work either).

So how can I do it?

过渡需要转到您要更改属性的位置,即在您的togglex函数中

d3.select(this).transition().duration(500).attr("cx", currentx);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM