将SVG文本更改为css自动换行

use*_*514 12 javascript css svg word-wrap d3.js

以下代码用于显示javascript树图的文本标签.

nodeEnter.append("svg:text")
        .attr("x", function(d) { return d._children ? -8 : -48; }) /*the position of the text (left to right)*/
        .attr("y", 3) /*the position of the text (Up and Down)*/

        .text(function(d) { return d.name; });
Run Code Online (Sandbox Code Playgroud)

这使用svg,它没有自动换行功能.如何更改这个正常段落

所以我可以使用CSS来自动换行.如何制作这个常规文本而不是svg文本?

Isi*_*oGH 13

这是使用D3自动换行文本的示例代码:

var nodes = [
    {title: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"}
]

var w = 960, h = 800;

var svg = d3.select("body").append("svg")
    .attr("width", w)
    .attr("height", h);

var vSeparation = 13, textX=200, textY=100, maxLength=20

var textHolder = svg.selectAll("text")
    .data(nodes)
    .enter().append("text")
    .attr("x",textX)
    .attr("y",textY)
    .attr("text-anchor", "middle")
    .each(function (d) {
        var lines = wordwrap(d.title, maxLength)

        for (var i = 0; i < lines.length; i++) {
            d3.select(this).append("tspan").attr("dy",vSeparation).attr("x",textX).text(lines[i])
        }
    });


function wordwrap(text, max) {
    var regex = new RegExp(".{0,"+max+"}(?:\\s|$)","g");
    var lines = []

    var line
    while ((line = regex.exec(text))!="") {
        lines.push(line);
    } 

    return lines
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*ohn 11

您可能想要使用SVG foreignObject标记,因此您可能会这样:

nodeEnter.append("foreignObject")
    .attr("x", function(d) { return d._children ? -8 : -48; }) /*the position of the text (left to right)*/
    .attr("y", 3) /*the position of the text (Up and Down)*/
    .attr("width", your_text_width_variable)
    .attr("height", your_text_height_variable)
    .append("xhtml:body")
    .append("p")
    .text(function(d) { return d.name; });
Run Code Online (Sandbox Code Playgroud)

以下是Mike Bostock给我的一个要点:https://gist.github.com/1424037

  • `foreignObject`似乎是唯一的解决方案,但请注意它在IE中不受支持(惊喜!) (4认同)