简体   繁体   中英

Change the color of nodes on double click in D3

I want the color of node to change on double click. ie On the first double click, it would turn black but on re-double clicking it, it would turn back to its original color. I am able to make it turn black on the first double click, but I'm not able to make it turn back to its original color. Thanks in advance and here is my code.

var gnodes = svg.selectAll('g.gnode')
                .data(graph.nodes)
                .enter()
                .append('g')
                .classed('gnode', true);

var node = gnodes.append("circle")
                 .attr("class", "node")
                 .attr("r", 5)
                 .style("fill", function(d) {return d.colr; })
                 .on('dblclick', function (d)
                 {
                         if (d3.select(this).style("fill") != "black")
                            {
                                d3.select(this).style("fill", "black");
                            }
                        else
                            {
                                d3.select(this).style("fill", function(d){return d.colr;});
                            }
                })
                .call(force.drag);

The issue you're having here is actually really tricky to spot.

You are checking whether the fill style is equal to the string "black" . The problem is, many browsers (including Chrome and FF) reformat color names to RGB strings. So, when you set the fill to "black" , it is converted to the RGB string "rgb(0, 0, 0)" . So actually, calling d3.select(this).style("fill") will return this rgb string rather than the color name, ensuring that the else branch of your code never runs.

You can avoid having to check the current state of your fill as a style string by using selection.each to store each circle's state as a boolean value and then register its double-click handler, which toggles the boolean and then branches based on its value. Try this:

var node = gnodes.append("circle")
  .attr("class", "node")
  .attr("r", 5)
  .style("fill", function(d) {return d.colr; })
  .each(function() {
    var sel = d3.select(this);
    var state = false;
    sel.on('dblclick', function() {
      state = !state;
      if (state) {
        sel.style('fill', 'black');
      } else {
        sel.style('fill', function(d) { return d.colr; });
      }
    });
  });

One way to handle this is via CSS:

.doubled { fill: black !important; }

Then toggle this CSS class in your dblclick function:

d3.selectAll(".node")
  .on("dblclick", function() {
    var c = d3.select(this).classed("doubled");
    d3.select(this).classed("doubled", !c);
  })

Working example here: http://jsfiddle.net/qAHC2/829/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM