通过单击更改节点的颜色

时间:2021-05-31 21:44:55

标签: javascript d3.js

如何更改节点的颜色?如果我点击一个以前是蓝色的节点,它应该改变颜色,例如到紫色。但是如果我现在点击另一个节点,这个节点应该变成紫色,之前点击的节点应该变成旧颜色(即再次变成蓝色)。我该怎么做?

const color = d3.scaleLinear().domain([0, 1]).range(["#03fc90", "#03dbfc"]);
var node = svg.append("g")
  .attr("class", "nodes")
  .selectAll("circle")
  .data(dataset.nodes)
  .enter()
  .append("circle")
  .attr("r", 5)
  .style("fill", function(d,i) {
    return color(i);})
   .on("click", (evt, currentNode) => {    
    d3.select(this).
    .style.color=’purple’
  });

1 个答案:

答案 0 :(得分:1)

  1. 在初始渲染时,为每个节点设置默认的 fill 样式。
  2. 点击后,找到之前选择的节点,移除“selected”类并设置默认颜色
  3. 对于新节点,设置“selected”类和颜色

const nodes = [
  {id: 1, x: 50, y: 50},
  {id: 2, x: 50, y: 100},
  {id: 3, x: 100, y: 75},
];

const svg = d3.select('svg');
  svg.selectAll('circle.node')
    .data(nodes, d => d.id)
    .enter()
    .append('circle')
    .classed('node', true)
    .attr('cx', d => d.x)
    .attr('cy', d => d.y)
    .attr('r', 20)
    .style('fill', 'blue')
    .style('cursor', 'pointer')
    .on('click', onClickNode);
  
function onClickNode (e, d) {
  svg.selectAll('.node.selected')
    .classed('selected', false)
    .style('fill', 'blue');
  
  d3.select(this)
    .classed('selected', true)
    .style('fill', 'purple');
}  
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script>

<svg />

相关问题