Can I move an SVG element between SVG groups, in d

2020-02-05 18:34发布

Can I move an SVG element between SVG groups - without stirring too much calculation behind the scenes nor crafting too much code in my own code? The d3 api documentation mentions you cannot re-append removed elements (?).

Recreating the element after removing it from its original group - may seem to be cumbersome in my code, and more expensive for d3 and the browser than it could be if that were possible.

This is also relevant for defining an element before associating it with a group, not just for really moving it between groups (i.e. for moving an element from a non-group to a group).

标签: svg d3.js
2条回答
\"骚年 ilove
2楼-- · 2020-02-05 19:05

You can't do this in D3, but JQuery has the .appendTo() function for that, e.g.

$("#element").appendTo("#otherGroup");
查看更多
迷人小祖宗
3楼-- · 2020-02-05 19:08

The docs you posted also mention that you can re-add the elements by passing a function to .append or .insert. Here's what it says:

Note that there is not currently a dedicated API to add removed elements back to the document; however, you can pass a function to selection.append or selection.insert to re-add elements.


Since using .remove on a selection returns that selection, you could store the removed element in a variable, and then .append it to the new group using selection.node() to grab the DOM element from the removed selection:

var removed = yourSelection.remove();
yourTargetGroup.append(function() {
  return removed.node();
});

Here's a simple Fiddle that uses this technique to move a circle element from one group to another in a click handler.

查看更多
登录 后发表回答