Can I move an SVG element between SVG groups, in d3.js

后端 未结 4 2067
心在旅途
心在旅途 2020-12-10 14:24

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 me

4条回答
  •  无人及你
    2020-12-10 15:01

    To just move around existing nodes within the DOM tree it is not necessary to first remove them to later re-append those same nodes at a different position. d3.append() internally uses Node.appendChild() which works as follows:

    If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

    This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position.

    As other answerers have already mentioned both selection.append() and selection.insert() when being passed a function will append or insert, respectively, the node returned by that function. Knowing that, all it takes to move around a DOM node from its current position to a new target is

    target.append(() => existingNode);  // target is a D3 selection, existingNode is a native DOM node
    

    Having this in your toolbox it is also fairly easy to move around multiple nodes at once:

    selectionToBeMoved.each(function() { target.append(() => this); });
    

    Have a look at the following demo to see it in action. The two circles colored in Aquamarine are move from group #g1 to group #g2.

    const current = d3.select("#g1");
    const target  = d3.select("#g2");
    
    current.selectAll("circle[fill=Aquamarine]")
      .each(function() { target.append(() => this); });
    
    
    
      
        
        
        
      
      
      
    

提交回复
热议问题