Set text width or put text in a div

2019-09-16 04:08发布

I would like to be able to set the width of a text element in D3. For now I have some text in a circle but I cannot set the width of this element. (let's say that nodeEnter is a node in my graph)

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");

What I would like is to find a simple way of setting the width of that text element (with the overflow going down, as in a simple div). The way I have right now is the following:

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"); 

However I don't think that it is the best solution, for example everything I set in myCSS is overwriten. Moreover I don't know how to center the foreign Object in the circle (especially on the x axis).

Thanks in advance for your help.

2条回答
beautiful°
2楼-- · 2019-09-16 04:53

If you want automatic line wrapping, foreignObject with a div is the way to go. The problems you mention can be fixed relatively easily. While you're setting myCSS for the svg element, you're not setting it for the div. If you add the line to set the CSS class after appending the div, it should pick up the settings.

The easiest way to center the text is probably to set the size of the div to touch the edges of the circle and add the CSS to center the text within the div.

查看更多
我想做一个坏孩纸
3楼-- · 2019-09-16 04:55

If you're just creating circles, you could always just use regular HTML elements to create the circles and absolute positioning to position them.

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; }

This also has the advantage of being supported on IE7 and IE8.

查看更多
登录 后发表回答