You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在D3.js中实现多关联节点的展开与折叠功能

实现D3.js力导向图的节点展开/折叠功能

我明白你现在的困境——现有代码里的点击事件没法获取子节点信息,核心问题在于你的links数据是扁平的关联关系,没有明确的父子层级定义,而且D3的力导向图默认是无向关联的。下面是一套完整的改造方案,帮你实现点击节点展开/折叠子节点的功能:

1. 重构数据,添加父子层级标识

首先我们需要给每个节点添加关联节点集合(当作子节点)和隐藏状态标记,这样点击时才能找到对应的子元素:

var nodes = {};
// 构建节点并建立关联关系
links.forEach(function(link) {
  // 初始化节点,添加隐藏状态、展开状态和子节点集合
  link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, _hidden: false, _expanded: true, children: []});
  link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, _hidden: false, _expanded: true, children: []});
  // 将目标节点添加为源节点的子节点(可根据type筛选,比如只把"suit"类型当作父子)
  link.source.children.push({node: link.target, link: link});
  // 如果需要双向折叠,取消下面注释,让源节点也成为目标节点的子节点
  // link.target.children.push({node: link.source, link: link});
});

2. 修改点击事件逻辑

现在点击节点时,我们可以通过节点的children属性拿到关联的子节点和连线,切换它们的显示状态,并更新力导向图布局:

function click(d) {
  // 切换当前节点的展开/折叠状态
  d._expanded = !d._expanded;
  
  // 遍历所有关联的子节点和连线,切换隐藏状态
  d.children.forEach(function(child) {
    child.node._hidden = !d._expanded;
    child.link._hidden = !d._expanded;
  });
  
  // 更新节点、连线、文本的显示状态
  circle.style("display", function(n) {
    return n._hidden ? "none" : "inline";
  });
  
  path.style("display", function(l) {
    return l._hidden ? "none" : "inline";
  });
  
  text.style("display", function(n) {
    return n._hidden ? "none" : "inline";
  });
  
  // 重启力导向图,让可见节点重新布局
  force.start();
}

3. 初始化时设置默认显示状态

在创建节点、连线和文本元素时,默认应用隐藏状态的样式:

// 连线初始化
var path = svg.append("g").selectAll("path")
  .data(force.links())
  .enter().append("path")
  .attr("class", function(d) { return "link " + d.type; })
  .style("display", function(d) { return d._hidden ? "none" : "inline"; })
  .attr("marker-end", function(d) { return "url(#" + d.type + ")"; });

// 节点初始化
var circle = svg.append("g").selectAll("circle")
  .data(force.nodes())
  .enter().append("circle")
  .attr("r", 6)
  .style("display", function(d) { return d._hidden ? "none" : "inline"; })
  .call(force.drag)
  .on('click', click);

// 文本初始化
var text = svg.append("g").selectAll("text")
  .data(force.nodes())
  .enter().append("text")
  .attr("x", 8)
  .attr("y", ".31em")
  .style("display", function(d) { return d._hidden ? "none" : "inline"; })
  .text(function(d) { return d.name; });

4. 优化力导向图布局(可选)

为了避免隐藏元素影响布局,我们在tick函数中只处理可见的元素:

function tick() {
  // 只更新可见的连线、节点和文本
  path.filter(function(d) { return !d._hidden; })
      .attr("d", linkArc);
  
  circle.filter(function(d) { return !d._hidden; })
      .attr("transform", transform);
  
  text.filter(function(d) { return !d._hidden; })
      .attr("transform", transform);
}

完整改造后的代码

// http://blog.thomsonreuters.com/index.php/mobile-patent-suits-graphic-of-the-day/ 
var links = [ 
  {source: "Samsung", target: "Apple", type: "suit"}, 
  {source: "Motorola", target: "Apple", type: "suit"}, 
  {source: "Nokia", target: "Apple", type: "resolved"}, 
  {source: "HTC", target: "Apple", type: "suit"}, 
  {source: "Kodak", target: "Apple", type: "suit"}, 
  {source: "Microsoft", target: "Barnes & Noble", type: "suit"}, 
  {source: "Microsoft", target: "Foxconn", type: "suit"}, 
  {source: "Oracle", target: "Google", type: "suit"}, 
  {source: "Apple", target: "HTC", type: "suit"}, 
  {source: "Microsoft", target: "Inventec", type: "suit"}, 
  {source: "Samsung", target: "Kodak", type: "resolved"}, 
  {source: "LG", target: "Kodak", type: "resolved"}, 
  {source: "RIM", target: "Kodak", type: "suit"}, 
  {source: "Sony", target: "LG", type: "suit"}, 
  {source: "Kodak", target: "LG", type: "resolved"}, 
  {source: "Apple", target: "Nokia", type: "resolved"}, 
  {source: "Qualcomm", target: "Nokia", type: "resolved"}, 
  {source: "Apple", target: "Motorola", type: "suit"}, 
  {source: "Microsoft", target: "Motorola", type: "suit"}, 
  {source: "Motorola", target: "Microsoft", type: "suit"}, 
  {source: "Huawei", target: "ZTE", type: "suit"}, 
  {source: "Ericsson", target: "ZTE", type: "suit"}, 
  {source: "Kodak", target: "Samsung", type: "resolved"}, 
  {source: "Apple", target: "Samsung", type: "suit"}, 
  {source: "Kodak", target: "RIM", type: "suit"}, 
  {source: "Nokia", target: "Qualcomm", type: "suit"} 
]; 

var nodes = {}; 

// 构建节点及父子关联关系
links.forEach(function(link) {
  link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, _hidden: false, _expanded: true, children: []});
  link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, _hidden: false, _expanded: true, children: []});
  link.source.children.push({node: link.target, link: link});
}); 

var width = 960, height = 500; 

var force = d3.layout.force() 
  .nodes(d3.values(nodes)) 
  .links(links) 
  .size([width, height]) 
  .linkDistance(60) 
  .charge(-300) 
  .on("tick", tick) 
  .start(); 

var svg = d3.select("body").append("svg") 
  .attr("width", width) 
  .attr("height", height); 

// 定义连线标记
svg.append("defs").selectAll("marker") 
  .data(["suit", "licensing", "resolved"]) 
  .enter().append("marker") 
  .attr("id", function(d) { return d; }) 
  .attr("viewBox", "0 -5 10 10") 
  .attr("refX", 15) 
  .attr("refY", -1.5) 
  .attr("markerWidth", 6) 
  .attr("markerHeight", 6) 
  .attr("orient", "auto") 
  .append("path") 
  .attr("d", "M0,-5L10,0L0,5"); 

// 创建连线
var path = svg.append("g").selectAll("path") 
  .data(force.links()) 
  .enter().append("path") 
  .attr("class", function(d) { return "link " + d.type; }) 
  .style("display", function(d) { return d._hidden ? "none" : "inline"; })
  .attr("marker-end", function(d) { return "url(#" + d.type + ")"; }); 

// 创建节点
var circle = svg.append("g").selectAll("circle") 
  .data(force.nodes()) 
  .enter().append("circle") 
  .attr("r", 6) 
  .style("display", function(d) { return d._hidden ? "none" : "inline"; })
  .call(force.drag) 
  .on('click', click); 

// 创建文本标签
var text = svg.append("g").selectAll("text") 
  .data(force.nodes()) 
  .enter().append("text") 
  .attr("x", 8) 
  .attr("y", ".31em") 
  .style("display", function(d) { return d._hidden ? "none" : "inline"; })
  .text(function(d) { return d.name; }); 

// 点击事件逻辑
function click(d) {
  d._expanded = !d._expanded;
  
  d.children.forEach(function(child) {
    child.node._hidden = !d._expanded;
    child.link._hidden = !d._expanded;
  });
  
  circle.style("display", function(n) {
    return n._hidden ? "none" : "inline";
  });
  
  path.style("display", function(l) {
    return l._hidden ? "none" : "inline";
  });
  
  text.style("display", function(n) {
    return n._hidden ? "none" : "inline";
  });
  
  force.start();
} 

// 连线绘制逻辑
function tick() {
  path.filter(function(d) { return !d._hidden; })
      .attr("d", linkArc);
  
  circle.filter(function(d) { return !d._hidden; })
      .attr("transform", transform);
  
  text.filter(function(d) { return !d._hidden; })
      .attr("transform", transform);
} 

function linkArc(d) { 
  var dx = d.target.x - d.source.x, dy = d.target.y - d.source.y, dr = Math.sqrt(dx * dx + dy * dy); 
  return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y; 
} 

function transform(d) { 
  return "translate(" + d.x + "," + d.y + ")"; 
} 
.link { fill: none; stroke: #666; stroke-width: 1.5px; } 
#licensing { fill: green; } 
.link.licensing { stroke: green; } 
.link.resolved { stroke-dasharray: 0,2 1; } 
circle { fill: #ccc; stroke: #333; stroke-width: 1.5px; } 
text { font: 10px sans-serif; pointer-events: none; text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js"></script>

关键说明

  • 如果你需要严格的父子层级(比如只把特定类型的关联当作父子),可以在添加children时加上判断条件,比如if(link.type === 'suit')。
  • 我们通过_hidden属性标记元素的显示状态,避免直接删除元素(删除后重新添加会增加复杂度)。
  • 每次切换显示后重启力导向图,让可见节点重新计算布局,避免出现布局混乱的情况。

内容的提问来源于stack exchange,提问作者test testing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:23:13