将 HTML 追加到 d3 中的现有工具提示



我正在尝试修改 zalando 技术雷达中的工具提示。

相关代码为:

  function showBubble(d) {
    if (d.active || config.print_layout) {
      var tooltip = d3.select("#bubble text")
        .text(d.label);
      var bbox = tooltip.node().getBBox();
      d3.select("#bubble")
        .attr("transform", translate(d.x - bbox.width / 2, d.y - 16))
        .style("opacity", 0.8);
      d3.select("#bubble rect")
        .attr("x", -5)
        .attr("y", -bbox.height)
        .attr("width", bbox.width + 10)
        .attr("height", bbox.height + 4);
      d3.select("#bubble path")
        .attr("transform", translate(bbox.width / 2 - 5, 3));
    }
  }

为了扩展工具提示,我尝试根据此处描述的解决方案执行以下操作。

我修改的代码:

function showBubble(d) {
    if (d.active || config.print_layout) {
      var tooltip = d3.select("#bubble text");
      tooltip.html("foo"); // this works!
      //tooltip.html(function(d) { d.label}) // d is undefinded here ...
      tooltip.append("div").attr("id", "foo");
      d3.select("#foo").html("This is not shown").attr("style", "block");
      var bbox = tooltip.node().getBBox();
      d3.select("#bubble")
        .attr("transform", translate(d.x - bbox.width / 2, d.y - 16))
        .style("opacity", 0.8);
      d3.select("#bubble rect")
        .attr("x", -5)
        .attr("y", -bbox.height)
        .attr("width", bbox.width + 10)
        .attr("height", bbox.height + 4);
      d3.select("#bubble path")
        .attr("transform", translate(bbox.width / 2 - 5, 3));
    }
  }

有人可以给我一个提示如何显示这个额外的文本吗?

更新

完整的代码 https://github.com/zalando/tech-radar

svg 中的多行文本与 HTML 略有不同。您不能只附加<div><br>标签,因为它们在SVG中没有任何意义。

因此,您的选择是:

  • 使用外来对象在 SVG 中呈现 HTML

var tooltip = d3.select("#bubble")
var fo = tooltip.append('foreignObject').attr('width', '100%').attr('height', '100%')
var foDiv = fo.append("xhtml:body").append("xhtml:div").attr('class', 'fe-div').style('background', '#ccc').html("foo <br>2nd line <br>3rd line")
html,
body,
svg {
  height: 100%
}
.fe-div {
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<svg viewBox="0 0 240 80" xmlns="http://www.w3.org/2000/svg">
  <g id="bubble">
  </g>
</svg>

  • 或者使用定位的 tspan 元素来分解文本,如下所示:

var tooltip = d3.select("#bubble text");
tooltip.html("foo"); // this works!
// Create a tspan for the 2nd line
var tspan1 = tooltip.append("tspan");
tspan1.html("2nd line");
tspan1.attr('x', 0).attr('dy', '1em')
// Create a tspan for the 3rd line
var tspan2 = tooltip.append("tspan");
tspan2.html("3rd line");
tspan2.attr('x', 0).attr('dy', '1em')
html,
body,
svg {
  height: 100%
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<svg viewBox="0 0 240 80" xmlns="http://www.w3.org/2000/svg">
  <g id="bubble">
    <text y="35"></text>
  </g>
</svg>

最新更新