簡體   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