首页 > 解决方案 > 更新数据后覆盖的 D3JS 换行文本插件

问题描述

我一直在使用此处接受的答案中的解决方案将文本包装在树形图上在 D3 中包装文本

不过,当我更新数据时,如下所示:

nodeUpdate
  .selectAll("text.nodeText")
  .text(function(d) {
    return d.name;
  })
  .call(wrap, 100)
  .style("fill-opacity", 1);

包裹效果消失

我究竟做错了什么?

____编辑以显示更多代码____

每个节点都添加了通常的 D3JS 过程(进入、更新、退出)。问题是包装更新的文本不起作用。

所以我们输入节点

var nodeEnter = node
  .enter()
  .append("g")
  .call(dragListener)
  .attr("class", "node")
  .attr("transform", function(d) {
    return "translate(" + source.y0 + "," + source.x0 + ")";
  })
  .on("click", click);

我们将元素附加到节点,例如感兴趣的文本:

nodeEnter 
  .append("text")
  .attr("x", 5)
  .attr("dy", ".95em")
  .attr("class", "nodeText")
  .attr("text-anchor", "start")
  .text(function(d) {
    return d.name;
  })
  .call(wrap, 150);

如果我们不更新这些节点,包装工作正常。但是在下面这样的更新中:

var nodeUpdate = node
  .transition()
  .duration(duration)
  .attr("transform", function(d) {
    return "translate(" + d.y + "," + d.x + ")";
  });

nodeUpdate
  .selectAll("text.nodeText")
  .text(function(d) {
    return d.name;
  })
  .style("fill-opacity", 1)
  .call(wrap, 130);

文本不再适合包装。wrap 函数来自上面引用的 stackoverflow,请查看链接。

标签: javascriptd3.jsupdatingword-wrap

解决方案


我刚刚在其他地方遇到了同样的问题。这是因为文本换行功能不能作用于过渡,它需要一个选择。要修复您的代码,只需在转换之前将文本添加和wrap调用移至:

node
  .selectAll("text.nodeText")
  .text(function(d) {
    return d.name;
  })
  .call(wrap, 130);

var nodeUpdate = node
  .transition()
  .duration(duration)
  .attr("transform", function(d) {
    return "translate(" + d.y + "," + d.x + ")";
  });

nodeUpdate
  .selectAll("text.nodeText")
  .style("fill-opacity", 1)

推荐阅读