【问题标题】:How do I do a line break with SVG text element ? [duplicate]如何使用 SVG 文本元素进行换行? [复制]
【发布时间】:2015-01-12 10:49:07
【问题描述】:

使用 D3 创建力图。我希望单击一个按钮并出现一个矩形(我已经完成了)。 现在我想在这个矩形文本中添加几行文本。

我要显示三个句子,每行一个,所以我知道应该在哪里换行。

这些我都试过了:

.text("test" + "\n" + "should be on second line");

.text("test" + "\\n" + "should be on second line");

.text("test" + "<br/>" + "should be on second line");

.html("test" + "\n" + "should be on second line");

.html("test" + "\\n" + "should be on second line");

.html("test" + "<br/>" + "should be on second line");

它们似乎都不起作用,我不确定为什么。我四处搜索,人们正在做一些黑客行为来解决这个问题。当然有更简单的方法吗?

【问题讨论】:

标签: javascript svg d3.js


【解决方案1】:

当我使用 D3 时,我已经弄清楚并为我工作。我创建了一个数组(我希望显示的文本),然后创建了一个函数,将数组拆分为单独的行。

var popUpTextArray = ["first line", "second line", "third line"];

function textMultipleRows(textArray, area, xPos, yPos){

    for(i=0;i<textArray.length;i++){
        d3.selectAll(area) //-area you wish to append the text to
        .append("text")
        .classed("popUpTextLeft", true) //-CSS class for the text
        .attr("x", xPos)
        .attr("y", yPos+(i*20)) //-new line when going through the loop
        .text(textArray[i]); //-goes through each element in the text array
    }   
}

textMultipleRows(popUpTextArray, "#window1", 300,200);

它有点 hacky,它由 D3 组成,所以我不知道是否有很多人会使用它,但正如我所说,它非常适合我。

【讨论】:

    猜你喜欢
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 2021-09-13
    • 2020-06-26
    • 2018-07-07
    • 2014-12-04
    相关资源
    最近更新 更多