简体   繁体   English

在SVG中使用HTML格式进行文本对齐

[英]Use HTML formatting in SVG for text alignment

I'm trying to make the numbers in this code line up regardless if they are positive or negative. 我正在尝试使此代码中的数字对齐,无论它们是正数还是负数。

 pointer_labels = ["PANTS", "SOCKS", "SHOES"] vals = [0, 0.8, -0.2] var svg = d3.select("#root").append("svg") var texts = svg.selectAll("text").data(pointer_labels); texts.enter() .append("text") .attr("x", 15) .attr("y", function(d, i) { return i * 20 + 9; }) .html(function(d, i) { var sign = '<foreignObject x="20" y="9" width="150" height="200">&nbsp;<span>&plus</span></foreignObject>'; if (vals[i] < 0) { sign = "&nbsp;&minus;"; } return pointer_labels[i] + " " + sign + Math.abs(vals[i]).toFixed(2); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <div id="root"> </div> 

I'm trying to accomplish this by inserting an invisible minus sign, but whenever I insert an HTML tag, the text isn't displayed, despite being inserted into the DOM. 我试图通过插入一个不可见的减号来实现此目的,但是无论何时插入HTML标记,尽管已插入到DOM中,文本也不会显示。 I've reviewed the questions similar to this one and have tried the foreignObject trick, but that doesn't seem to be working either. 我已经审查了与此类似的问题,并尝试了foreignObject技巧,但这似乎也不起作用。

Note that the reason I'm using SVG despite the fact that I seem only to be working with text, is that this is actually for plot legends that I'm making. 请注意,尽管我似乎仅在处理文本,但我仍使用SVG的原因是,这实际上是针对我正在制作的图例。 This is how it looks in the actual application: 这是实际应用中的样子: 在此处输入图片说明

Thanks to Gildor's comment, I figured out that if I just created a separate text element for the numbers and align it to the right, I get the same effect. 多亏了吉尔多尔(Gildor)的评论,我才知道,如果我只是为数字创建一个单独的文本元素并将其向右对齐,我将获得相同的效果。

 pointer_labels = ["PANTS", "SOCKS", "SHOES"] vals = [0, 0.8, -0.2] var svg = d3.select("#root").append("svg") var texts = svg.selectAll("g").data(pointer_labels); var txt_enter = texts.enter(); txt_enter.append("text") .attr("x", 15) .attr("y", function(d, i){ return i * 20 + 9;}) .text(function(d, i) { return pointer_labels[i]}); txt_enter.append("text") .attr("x", 300) .attr("y", function(d, i){ return i * 20 + 9;}) .attr("text-anchor","end") .html(function(d, i) { var sign = ''; if(vals[i] < 0){ sign = "&minus;"; } return sign + Math.abs(vals[i]).toFixed(2); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <div id="root"> </div> 

Basically, if you can avoid using html inside SVG, you should. 基本上,如果可以避免在SVG中使用html,则应该这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM