[英]Is it possible to append text to a text element in SVG?
我試圖在點擊該特定文本時在數據標簽的末尾附加一個新的文本元素。 可能嗎? 我試圖將此添加到我的代碼中,它不顯示要添加的文本:
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;});
});
但它已被附加到數據標簽。
為什么“[A]”文本即使在附加到父文本元素后也不會顯示?
簡短回答:您不能將<text>
元素附加到另一個<text>
元素。
根據SVG規范 ,
文本內容子元素是允許作為另一文本內容元素的后代的文本內容元素。 在SVG 1.1中,文本內容子元素如下:'altGlyph','textPath','tref'和'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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.