javascript - 更改选定节点样式,d3.js 可折叠缩进树

标签 javascript d3.js tree

我试图通过突出显示树中的“选定”节点以及显示类似于加号/减号的图标来让用户更直观地表示他们在树中的位置显示了 children 。

我似乎无法在任何地方找到如何做到这一点,因为似乎在展开后重新绘制树后,所选节点信息就消失了,无法对其进行操作。目前我的树节点突出显示基于隐藏/显示或没有任何 child ,但我想跟踪哪个节点被点击了填充颜色。我的树基于 mbostock 的区 block #1093025。对于加号/减号图标切换以及突出显示所选节点,我们将不胜感激。

显示展开/折叠图标的当前代码:

nodeEnter.append("svg:image")
    .attr("xlink:href", function(d) {
        if (d._children) return "images/arrow_right.png";
        else if (d.children) return "images/arrow_left.png";
    })
    .attr("x", "-12px")
    .attr("y", "-10px")
    .attr("width", 15)
    .attr("width", 20);

使用调整大小功能放大选定节点的功能...根本无法使这些功能正常工作,或者无法在重绘时识别选定节点。只有填充似乎可以识别所选节点。

nodeEnter.append("rect")
    .attr("y", newy)
    .attr("height", newheight)
    .attr("width", barWidth)
    .style("fill", color)
    .on("click", click);

function newy(d) {
    if (d._isSelected)
        return -barHeight / 1.25;
    else
        return -barheight/2;
}
function newheight(d) {
    if (d._isSelected)
        return barHeight * 1.75;
    else
        return barheight;
}

最佳答案

只是因为示例代码“忘记”了所选节点,并不意味着您不能自己添加它:

// Toggle children on click.
var lastClickD = null;
function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  if (lastClickD){
    lastClickD._isSelected = false;
  }
  d._isSelected = true;
  lastClickD = d;
  update(d);
}

// on the selected one change color to red
function color(d) {
  if (d._isSelected) return 'red';
  return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c";
}

要添加展开/折叠指示器,只需根据其子状态更新重绘节点:

// we used to set the text on enter
nodeEnter.append("text")
  .attr("dy", 3.5)
  .attr("dx", 5.5); 

// but now we change it on update based on children
node.select('text') 
  .text(function(d) { 
    if (d.children) {
      return '+' + d.name;
    } else if (d._children) {
      return '-' + d.name;
    } else {
      return d.name;
    }
  });

这是一个 example .

关于javascript - 更改选定节点样式,d3.js 可折叠缩进树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606998/

相关文章:

javascript - 遍历json抽象语法树构建 boolean 表达式

c# - 如何使用 TreeView 转换器从列表创建树结构?

javascript - 如何使一个 Jquery 脚本适用于名称略有不同的多个输入

javascript - 如何检测使用的是 Android 浏览器还是 Android native WebView 客户端

javascript - 如何处理单击 D3.js 按钮时的数据过滤?

java - 是否可以读取.txt文件的文件名并将其写入二叉树?

javascript - 谷歌地图标记点击,显示模态

javascript - gulp-ruby-sass 的语法错误似乎不正确

d3.js 在非 svg 元素上强制布局

javascript - D3 : Resizing x axis and repositioning circles