[英]How to create a line break in an HTML element using D3.js
I can't seem to format my tooltip into 4 separate lines. 我似乎无法将工具提示格式化为4行。 I have ap element and want to break it up.
我有ap元素,想分手。 I have tried adding br and \\n and they don't seem to help.
我尝试添加br和\\ n,但它们似乎无济于事。
var tooltip = d3.select("body")
.append("div")
.attr('class', 'tooltip');
tooltip.append("p");
//Here I go through my data using selectAll and append circles. //在这里,我使用selectAll查看数据并附加了圆圈。 the '.on' attribute is when I hover over a circle I want to see the tooltip
“ .on”属性是当我将鼠标悬停在一个圆圈上时,我希望看到工具提示
.on("mousemove", function(d){
if (d.source == "target") {
tooltip.select("p").text(d.source);
} else {
tooltip.select("p").text("Line 1: " + "this is line 1" + "\n" + "line 2: " + "this is line 2");
}
Instead of using .text()
, use .html()
, that way you can use <br>
like so: 不用
.text()
而是使用.html()
,那样您就可以像这样使用<br>
:
tooltip.select("p").html("Line1: this is line 1 <br> line 2: this is line 2");
If that doesn't work, try 如果这不起作用,请尝试
tooltip.select("p").html(function(){
return "Line 1: this is line 1 <br> line 2: this is line 2"
});
As this is how I currently use .html()
因为这是我目前使用
.html()
Just as a complement to the other answer : 作为对其他答案的补充:
You can use either html()
or text()
methods here. 您可以在此处使用
html()
或text()
方法。 The difference between them is that text()
uses textContent
, while html()
uses innerHTML
. 它们之间的区别在于
text()
使用textContent
,而html()
使用innerHTML
。
We can see this at the source code for text()
: 我们可以在
text()
的源代码中看到这一点:
this.textContent = value;
And this at the source code for html()
: 这是
html()
的源代码 :
this.innerHTML = value;
Therefore, each method has its particularities. 因此,每种方法都有其特殊性。
Using html() 使用html()
As already explained, you can use html()
with <br>
: 如前所述,您可以将
html()
与<br>
:
d3.select("p").html("Line 1: " + "this is line 1" + "<br>" + "line 2: " + "this is line 2");
<p></p> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
Using text() 使用text()
For using the text()
method, just as in your code, you have to select an adequate value for white-space , like pre
: 与在代码中一样,使用
text()
方法时,必须为空白选择足够的值,例如pre
:
var p = d3.select("p"); p.text("Line 1: " + "this is line 1" + "\\n" + "line 2: " + "this is line 2");
p { white-space: pre; }
<p></p> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.