我可以在 d3.js 中的 SVG 组之间移动 SVG 元素吗 [英] Can I move an SVG element between SVG groups, in d3.js

查看:20
本文介绍了我可以在 d3.js 中的 SVG 组之间移动 SVG 元素吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 SVG 组之间移动一个 SVG 元素吗 - 无需在幕后进行过多的计算,也无需在我自己的代码中编写过多的代码?d3 api 文档 提到您不能重新附加已删除的元素 (?).

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 mentions you cannot re-append removed elements (?).

从原始组中删除元素后重新创建元素 - 在我的代码中可能看起来很麻烦,而且对于 d3 和浏览器来说比可能的情况更昂贵.

Recreating the element after removing it from its original group - may seem to be cumbersome in my code, and more expensive for d3 and the browser than it could be if that were possible.

这也与在将元素与组关联之前定义元素有关,而不仅仅是在组之间真正移动它(即,将元素从非组移动到组).

This is also relevant for defining an element before associating it with a group, not just for really moving it between groups (i.e. for moving an element from a non-group to a group).

推荐答案

您发布的文档提到您可以通过将函数传递给 .append.insert 来重新添加元素.这是它所说的:

The docs you posted also mention that you can re-add the elements by passing a function to .append or .insert. Here's what it says:

请注意,目前没有专门的 API 来将删除的元素添加回文档;但是,您可以将函数传递给 selection.append 或 selection.insert 以重新添加元素.

Note that there is not currently a dedicated API to add removed elements back to the document; however, you can pass a function to selection.append or selection.insert to re-add elements.


因为在选择上使用 .remove 会返回该选择,所以您可以将删除的元素存储在一个变量中,然后使用 .append 将其添加到新组中>selection.node() 从删除的选择中获取 DOM 元素:


Since using .remove on a selection returns that selection, you could store the removed element in a variable, and then .append it to the new group using selection.node() to grab the DOM element from the removed selection:

var removed = yourSelection.remove();
yourTargetGroup.append(function() {
  return removed.node();
});

这是一个简单的Fiddle,它使用这种技术将圆形元素从一组移动到另一组点击处理程序.

Here's a simple Fiddle that uses this technique to move a circle element from one group to another in a click handler.

这篇关于我可以在 d3.js 中的 SVG 组之间移动 SVG 元素吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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