使用 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");
它们似乎都不起作用,我不确定为什么。我四处搜索,人们正在做一些黑客来解决这个问题。当然有更简单的方法吗?
我已经弄明白了,并且在我使用 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);
它有点老套,它由 D3 组成,所以我不知道是否有很多人会使用它,但正如我所说,它非常适合我。