繁体   English   中英

如何使用D3.js在HTML元素中创建换行符

[英]How to create a line break in an HTML element using D3.js

我似乎无法将工具提示格式化为4行。 我有ap元素,想分手。 我尝试添加br和\\ n,但它们似乎无济于事。

var tooltip = d3.select("body")
    .append("div")
    .attr('class', 'tooltip');

tooltip.append("p");

//在这里,我使用selectAll查看数据并附加了圆圈。 “ .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");
}

不用.text()而是使用.html() ,那样您就可以像这样使用<br>

tooltip.select("p").html("Line1: this is line 1 <br> line 2: this is line 2");

如果这不起作用,请尝试

tooltip.select("p").html(function(){
    return "Line 1: this is line 1 <br> line 2: this is line 2"
});

因为这是我目前使用.html()

作为对其他答案的补充:

您可以在此处使用html()text()方法。 它们之间的区别在于text()使用textContent ,而html()使用innerHTML

我们可以在text()源代码中看到这一点:

this.textContent = value;

这是html()源代码

this.innerHTML = value;

因此,每种方法都有其特殊性。

使用html()

如前所述,您可以将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> 

使用text()

与在代码中一样,使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM