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

Wrap existing SVG elements in G tag

本文关键字:包装 元素 SVG      更新时间:2023-09-26

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

如果您将一个现有的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
});

这有点乱,因为d3期望你总是使用函数来确定插入或插入之前的元素,当我们在each语句中做这一切时,这是不必要的。但它应该能完成任务!

(或者,如果您的页面上已经有了这个库,可以使用JQuery方法。JQuery处理 SVG元素通常没有任何问题,它只是无法创建它们!)

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

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

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