通过单击d3选择/取消选择

时间:2016-04-21 01:10:32

标签: javascript d3.js

我正在尝试选择/取消选择点击的行(链接)。但是我已经有了鼠标悬停功能它应该与鼠标悬停不同,当我选择一条线条的颜色需要改变时,它需要绘制一个饼图并且取消选择也应该可以点击。

我有什么:

    nodeenter.on("mouseover", function(d){ 
console.log(d); 
 d3.select(this).attr("fill", "yellow");

return tooltip.style("visibility", "visible").text("This node's id is: " + d.id + " and " + "Name: " + d.name );})
.on("mousemove", function(){

    return tooltip.style("top",
    (d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(d){
    d3.select(this).attr("fill", "rgb(0, 0, " +(d*10) + ")");
    return tooltip.style("visibility", "hidden");});

link.on("mouseover", function(d){
    console.log(d)
     d3.selectAll('.'+d.id).style('stroke','aqua');
    return tooltip.style("visibility", "visible").text("This line's id is: " + d.id + " and " + "Name: " + d.name);})
.on("mousemove", function(){return tooltip.style("top",
    (d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(d){
     d3.selectAll('.'+d.id).style('stroke','black');
     return tooltip.style("visibility", "hidden");});

//to select
link.on("click", function(d){
  if (!d3.select(this).classed("selected") ){
     d3.select(this).classed("selected", true)
     d3.select(this).style("stroke","red");
  }else{
     d3.select(this).classed("selected", false);
     d3.select(this).style("stroke","black");
  }
});

1 个答案:

答案 0 :(得分:2)

结果如下:https://jsfiddle.net/xcn35ycm/4/

我将点击功能绑定到链接。

links.on("click", function(d){
  if (!d3.select(this).classed("selected") ){
     d3.select(this).classed("selected", true)
     d3.select(this).transition().attr("stroke","red");
  }else{
     d3.select(this).classed("selected", false);
     d3.select(this).transition().attr("stroke","black");
  }

并更新mouseout功能

.on("mouseout", function(d){
   if(!d3.select(this).classed("selected") ){
     d3.selectAll('.'+d.id).style('stroke','black');
     return tooltip.style("visibility", "hidden");
   }
});