【问题标题】:How to create a line break in an HTML element using D3.js如何使用 D3.js 在 HTML 元素中创建换行符
【发布时间】:2019-01-09 07:39:17
【问题描述】:

我似乎无法将我的工具提示格式化为 4 个单独的行。我有一个 p 元素,想分解它。我已尝试添加 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");
}

【问题讨论】:

    标签: javascript html d3.js


    【解决方案1】:

    不要使用.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()的方式

    【讨论】:

      【解决方案2】:

      作为对other answer的补充:

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

      我们可以在source code 看到这个text()

      this.textContent = value;
      

      这在source codehtml()

      this.innerHTML = value;
      

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

      使用 html()

      如前所述,您可以将html()&lt;br&gt; 一起使用:

      d3.select("p").html("Line 1: " + "this is line 1" + "&lt;br&gt;" + "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() 方法,就像在您的代码中一样,您必须为white-space 选择适当的值,例如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>

      【讨论】:

        猜你喜欢
        • 2022-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-29
        • 1970-01-01
        相关资源
        最近更新 更多