将现有的SVG元素包装在G标签中 [英] Wrap existing SVG elements in G tag

查看:52
本文介绍了将现有的SVG元素包装在G标签中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 (i.e. group) using d3.js, the way .wrap() works in 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?

推荐答案

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

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.

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 语句中全部完成操作时,则不必这样做.但这应该可以完成工作!

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. But it should get the job done!

(或者,如果您的页面上已有库,请使用JQuery方法.JQuery通常操作 SVG元素没有任何问题,只是无法创建它们!)

(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!)

这篇关于将现有的SVG元素包装在G标签中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆