通过在d3中单击来选择/取消选择

selecting/deselecting by clicking in d3

本文关键字:选择 取消 单击 d3      更新时间:2023-09-26

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

我所拥有的:

    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");
  }
});

结果如下: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");
  }

并更新鼠标输出功能

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