gpt4 book ai didi

javascript - 是否可以将文本附加到 SVG 中的文本元素?

转载 作者:行者123 更新时间:2023-11-29 10:04:07 25 4
gpt4 key购买 nike

我试图在单击该特定文本时在数据标签的末尾附加一个新的文本元素。是否可以?我试图将它添加到我的代码中,但它没有显示要添加的文本:

circleGroup.selectAll("text")
.data(data)
.enter()
.append("text")
.text(function (d) {
if (d.label) {
return d.label;
}
return "";
})
.attr("x", function (d) {
return x(d.time) + 6;
})
.attr("y", function (d) {
return y(d.plotY) + 4;
})
.attr("font-size", "10px")
.attr("fill", "#2d3d45")
.on("click", function(d) {
d3.select(this).append("text").text("[A]").attr("x", function(d) {return x(d.time) + 25;}).attr("y", function(d) { return y(d.plotY) + 4;});

});

但它已经附加到数据标签上了。

enter image description here

为什么“[A]”文本在附加到父文本元素后仍未显示?

最佳答案

简短回答:您不能附加一个<text>元素到另一个 <text>元素。

根据SVG specs ,

A text content child element is a text content element that is allowed as a descendant of another text content element. In SVG 1.1, the text content child elements are the following: ‘altGlyph’, ‘textPath’, ‘tref’ and ‘tspan’.

因此,解决方案是附加一个 <tspan>相反:

var svg = d3.select("svg");
svg.append("text")
.attr("x", 20)
.attr("y", 20)
.text("I am the text element")
.append("tspan")
.attr("dy", "1.5em")
.attr("x", 20)
.text("And I am the tspan element")
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

这会给你这个结构:

<text x="20" y="20">I am the text element
<tspan dy="1.5em" x="20">And I am the tspan element</tspan>
</text>

关于javascript - 是否可以将文本附加到 SVG 中的文本元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47541727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com