问题
I have a tree with on click event listeners. I'd like to re-centre my tree on whichever node the user clicked.
How do I get the actual x / y values of a tree node inside the click event?
回答1:
To get the x/y you must translate the nodes back through whatever translation you've already applied:
http://jsfiddle.net/WLaVU shows a working example of what you want.
// click event handler
function click_handler(d)
{
// these dudes must be smooshed back through the same transform
var x = xs(d);
var y = ys(d);
// normalize for width/height
var new_x = (-x + (width / 2));
var new_y = (-y + (height / 2));
// move the main container g
svg.attr("transform", "translate(" + new_x + "," + new_y + ")");
}
来源:https://stackoverflow.com/questions/18924778/get-coordinates-of-clicked-on-node-in-d3-tree-and-centre