在G标签中包装现有的SVG元素

dre*_*ore 7 javascript svg d3.js

这似乎是一个简单的问题要回答,但我很难这样做:是否有可能使用d3.js在新的SVG g标签(即组)中"包装"现有的SVG形状.wrap()适用于jQuery?如果我只是"手动"创建一个新的g标签,那么我将如何将现有元素移动到该g?

Ame*_*aBR 9

如果将现有DOM元素传递给appendinsert,则元素(及其子元素)将从DOM层次结构中的当前位置移动到您刚刚插入它们的位置.

var stuffToBeWrapped = d3.selectAll(".stuff");

stuffToBeWrapped.each(function() {

   d3.select( this.parentNode ).insert("g", function(){return this;} ) 
              //insert a new <g> element immediately before this element
     .attr("class", "wrapper") //set anything you want to on the <g>
     .append( function(){return this;} );
             //move the content element into the group

});
Run Code Online (Sandbox Code Playgroud)

它有点乱,因为d3希望你总是使用函数来确定之前要插入或插入的元素,而当我们在一个each语句中完成所有操作时,这是不必要的.但它应该完成工作!

(或者,如果你已经在你的页面上有了库,那么使用JQuery方法.JQuery通常不会有任何操纵 SVG元素的问题,它只是无法创建它们!)


Roy*_*rot 5

无法使 @AmeliaBR 的答案起作用,我这样解决了问题

d3.selectAll(selectElementsToWrap).each(function() {
    var el = this;
    d3.select(el.parentNode)
      .insert("g")
      .attr("class", "wrapped")
      .append(function() { return el; });
});
Run Code Online (Sandbox Code Playgroud)

批准的解决方案给了我 DOMException: Failed to execute 'appendChild' on 'Node': The new child element contains the parent