D3将文本附加到SVG矩形

gba*_*bam 63 javascript svg d3.js

我希望将html附加到D3中的矩形上,以便为我提供多行工具提示.底部是我如何添加一个矩形,这可能是问题的一部分.顶部是应该在我的世界中工作的代码.

 newRect.().html(" <textArea font-family=Verdana font-size=20 fill=blue > Test " + "</br>" + "Test2 </textArea>");
Run Code Online (Sandbox Code Playgroud)

哪个插入文本字段到SVG,它只是不显示:
HTML:

<rect id="rectLabel" x="490" y="674" width="130" height="160" fill="red">
    <textarea fill="blue" font-size="20" font-family="Verdana"> Test </br>Test2 </textarea>
</rect>
Run Code Online (Sandbox Code Playgroud)

我有一个鼠标悬停功能,运行如下:

    newRect = svg.append("rect")
    .attr("x", xCor)
    .attr("y", yCor)
    .attr("width", 130)
    .attr("height", 160)
    .attr("fill", "red")
    .attr("id", "rectLabel");
Run Code Online (Sandbox Code Playgroud)

我想我应该这样做,但它不起作用.它只是删除了我想要追加的g.node.

    newRect = $(this).enter().append("rect")
    .attr("x", xCor)
    .attr("y", yCor)
    .attr("width", 130)
    .attr("height", 160)
    .attr("fill", "red")
    .attr("id", "rectLabel");
Run Code Online (Sandbox Code Playgroud)

问题:为什么我的文字没出现?我试过.html,.textArea.我想要一个多行标签,所以我不认为.text会正常工作吗?另外,我应该如何追加矩形呢?

Ada*_*rce 115

A rect不能包含text元素.而是g使用文本和矩形的位置转换元素,然后将矩形和文本附加到它:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });
Run Code Online (Sandbox Code Playgroud)

http://bl.ocks.org/mbostock/7341714

多行标签也有点棘手,您可能想要查看此包装功能.


cba*_*ram 8

你试过SVG 文本元素吗?

.append("text").text(function(d, i) { return d[whichevernode];})
Run Code Online (Sandbox Code Playgroud)

rect元素不允许文本元素在其中.它只允许描述元素(<desc>, <metadata>, <title>)和动画元素(<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

将文本元素附加为兄弟元素并进行定位.

UPDATE

使用g分组,这样的事情怎么样?小提琴

您当然可以将逻辑移动到可以附加到的CSS类中,从组中删除(this.parentNode)