javascript - d3 如何在现有其他元素之前插入新的 SVG 元素?

标签 javascript d3.js svg

感谢this question我想我已经学会了如何做到这一点,但我不太相信我已经做对了,因为它很丑,正如你喜欢的那样。

假设有一个元素 #foo,我想在它之前创建一个 SVG 元素。我真的必须这样做吗:

var svg = d3.select(d3.select('#foo').node().parentNode)
  .insert('svg', '#foo')

我错过了什么吗? (编辑:要明确的是,上面的示例代码确实有效,但它非常不透明并且包含选择器的重复。)

最佳答案

您只需要类型选择器:

selection.insert(type, before)

例如,在此演示中,圆圈是 ID 为 foo 的元素。所以,

var svg2 = svg.insert("svg", "#foo");

在圆形元素之前插入子 SVG。

var svg = d3.select("body").append("svg")
var circle = svg.append("circle").attr("id", "foo");
var svg2 = svg.insert("svg", "#foo");
svg2.attr("id", "childSVG");

var mySVG = (new XMLSerializer()).serializeToString(svg.node());
console.log(mySVG)
<script src="https://d3js.org/d3.v4.min.js"></script>

关于javascript - d3 如何在现有其他元素之前插入新的 SVG 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40632150/

相关文章:

javascript - 刷事件动画时 brush.event 做什么?

javascript - 使用位置 :sticky for the bottom of a div Container

javascript - D3js : mouseover of one element change opacity of several others elements

javascript - 来自 csv 数据的 X 轴时间刻度

javascript - 在 D3 map 中显示事件列表

android - 如何在 react-native 上使用 svg 图像?

SVG 路径检测重叠或封闭的形状

javascript - 查找两个字符串正则表达式中常见出现的单词

javascript - 读取具有 "error"属性的元素并发出警报

javascript - 使用 greasemonkey 脚本自动化 flash 应用程序