Problems when using the insert() function in d3 ja

2019-08-30 08:03发布

问题:

I have problems using the insert() function of the d3 visualization library. Better to say I do not understand how to use the "before selector". I red the examples here and here, but this dod not help.

I create an svg element and append an element to it. Then I append foreignObject-element to the group and would like afterward insert an rectangle before the foreignObject-element.

Here is my code

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);

Here is a (non)working Jsfidle example

回答1:

EDIT: Try passing an id to the before select, as shown here: http://jsfiddle.net/GCTuD/3/

var rect1 = group.insert("svg:rect", "#foreign_object")

You cannot select by element tag name, only by constants (such as an id), as specified in the 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.