简体   繁体   English

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

[英]Wrap existing SVG elements in G tag

This seems like it'd be a simple question to answer but I'm having a hard time doing so: Is it possible to "wrap" existing SVG shapes in a new SVG g tag (ie group) using d3.js, the way .wrap() works in jQuery? 这似乎是一个简单的问题要回答,但我很难这样做:是否有可能使用d3.js在新的SVG g标签(即组)中“包装”现有的SVG形状.wrap()在jQuery中工作? If I were to simply create a new g tag "manually", how would I then go about moving an existing element into that g? 如果我只是“手动”创建一个新的g标签,那么我将如何将现有元素移动到该g?

If you pass an existing DOM element to append or insert , the element (and it's children) will be moved from their current place in the DOM hierarchy to wherever you've just inserted them. 如果将现有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

});

It's a little messy because d3 expects you to always use functions to determine which element to insert or insert before, and that's not necessary when we're doing it all within an each statement. 这有点乱,因为d3希望你总是使用函数来确定之前要插入或插入的元素,并且当我们在each语句中完成所有操作时,这是不必要的。 But it should get the job done! 但它应该完成工作!

(Or, use the JQuery method if you've already got the library on your page. JQuery doesn't usually have any problem manipulating SVG elements, it just can't create them!) (或者,如果你已经在你的页面上有了库,那么使用JQuery方法.JQuery通常不会有任何操纵 SVG元素的问题,它只是无法创建它们!)

Unable to make @AmeliaBR 's answer to work, I solved the problem like so 由于无法使@AmeliaBR的工作得到解决,我解决了这个问题

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM