设置文本宽度或将文本放在div中

时间:2012-12-10 15:13:29

标签: javascript svg d3.js

我希望能够在D3中设置文本元素的宽度。现在我在圆圈中有一些文字,但是我无法设置这个元素的宽度。 (假设nodeEnter是我图中的一个节点)

nodeEnter.append("circle")
    .attr("r", function(d){return d.radius+"px";});

/* Add text in middle of circle */
nodeEnter.append('text')
    .text("this is a very long text");

我想要的是找到一种简单的方法来设置该文本元素的宽度(溢出下降,如简单的div)。我现在的方式如下:

nodeEnter.append("circle")
    .attr("r", function(d){return d.radius+"px";});

/* Add text in middle of circle */ 
nodeEnter.append("foreignObject")
    .attr("width", 130)
    .attr("height", 200)
    .attr("class", "myCSS")
    .append("xhtml:div")
    .html("this is a very long text"); 

但是我不认为这是最好的解决方案,例如我在myCSS中设置的所有内容都会被覆盖。此外,我不知道如何将外来物体置于圆中(特别是在x轴上)。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

如果您想要自动换行,foreignObject div就行了。你提到的问题可以相对容易地修复。在为svg元素设置myCSS时,您不会为div设置它。如果在追加div后添加行来设置CSS类,则应该选择设置。

将文字居中的最简单方法可能是设置div的大小以触及圆的边缘,并添加CSS以使文本居中于div

答案 1 :(得分:1)

如果你只是创建圈子,你可以随时使用常规HTML元素来创建圆圈和绝对定位来定位它们。

http://jsfiddle.net/FPkxV/

HTML:

<p><span></span><span>This is some text which will wrap if it gets too long!</span></p>​

CSS:

* { margin: 0; padding: 0; }
body { font: 10px sans-serif; }
p { 
    background: red;
    text-align: center;
    border-radius: 50px; 
    width: 100px; 
    height: 100px; }
p span { 
    vertical-align: middle;
    display: inline-block; }
p span:first-child { height: 100px; }

这也具有being supported on IE7 and IE8.

的优势
相关问题