我在使用 insert() function 时遇到问题d3 可视化库的。更好地说我不明白如何使用“选择器之前”。我红色的例子here和 here ,但这没有帮助。
我创建一个 svg 元素并向其附加一个元素。然后我将foreignObject-element附加到该组中,并希望随后在foreignObject-element之前插入一个矩形。
这是我的代码
var body = d3.select("body");
var svg = body.append("svg")
.attr("width", '100%')
.attr("height", '100%');
var group = svg.append("svg:g");
var html = group.append("foreignObject")
.attr("x", 50)
.attr("y", 25)
.attr("width", 200)
.attr("height", 100)
.append("xhtml:div")
.style("font", "14px 'Helvetica Neue'")
.html("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam.");
var rect1 = group.insert("svg:rect", html)
.attr("rx", 6)
.attr("ry", 6)
.attr("x", 5/2)
.attr("y", 5/2)
.attr("id", "rect")
.attr("width", 250)
.attr("height", 120)
.style("fill", 'white')
.style("stroke", d3.scale.category20c())
.style('stroke-width', 5);
这是一个(非)工作 Jsfidle example
最佳答案
编辑:尝试将 id 传递给之前的选择,如下所示:http://jsfiddle.net/GCTuD/3/
var rect1 = group.insert("svg:rect", "#foreign_object")
您不能按元素标签名称进行选择,只能按常量(例如 id)进行选择,如 docs 中指定的那样。 :
The name and before selector must be specified as constants, though in the future we might allow inserting of existing elements or a function to generate the name or selector dynamically.
关于javascript - 尝试在另一个 SVG 元素之前插入 SVG 元素时使用 d3 java 库中的 insert() 函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16338098/