d3工具提示选择不是按类名

时间:2016-09-06 13:51:29

标签: javascript d3.js svg

我想在mouseout事件中从我的SVG对象中删除工具提示,但我不想按类名选择它。有没有其他方法可以选择它?也许我可以为它添加一个id属性,然后选择它?

  state.selectAll("rect")
       .on("mouseover", function(d){

          var delta = d.y1 - d.y0;
          var group = d3.select(d3.select(this).node().parentNode);
          var xPos = d3.transform(group.attr("transform")).translate[0];
          var yPos = parseFloat(d3.select(this).attr("y"));
          var height = parseFloat(d3.select(this).attr("height"))
          var width = parseFloat(d3.select(this).attr("width"))

          d3.select(this).attr("stroke","red").attr("stroke-width",0.8);

          svg.append("text")
          .attr("x",xPos)
          .attr("y",yPos + height/2)
          .attr("font-family", "sans-serif")
          .attr("font-size", "10px")
          .attr("font-weight", "bold")
          .attr("fill", "black")
          .attr("text-anchor", "middle")
          //.attr("class", "tooltip")
          .attr("transform", "translate(" + width/2 + ")")
          .text(d.name +": "+ delta);

       })
       .on("mouseout", function(){
          svg.select(".tooltip").remove(); // don't want to use that line
          d3.select(this).attr("stroke","pink").attr("stroke-width",0.2);

        });

1 个答案:

答案 0 :(得分:0)

啊,这似乎有效:

state.selectAll("rect")
                   .on("mouseover", function(d){

                      var delta = d.y1 - d.y0;
                      var group = d3.select(d3.select(this).node().parentNode);
                      var xPos = d3.transform(group.attr("transform")).translate[0];
                      var yPos = parseFloat(d3.select(this).attr("y"));
                      var height = parseFloat(d3.select(this).attr("height"))
                      var width = parseFloat(d3.select(this).attr("width"))

                      d3.select(this).attr("stroke","red").attr("stroke-width",0.8);

                      svg.append("text")
                      .attr("x",xPos)
                      .attr("y",yPos + height/2)
                      .attr("font-family", "sans-serif")
                      .attr("font-size", "10px")
                      .attr("font-weight", "bold")
                      .attr("fill", "black")
                      .attr("text-anchor", "middle")
                      .attr("id", "tooltip")
                      //.attr("class", "tooltip")
                      .attr("transform", "translate(" + width/2 + ")")
                      .text(d.name +": "+ delta);

                   })
                   .on("mouseout", function(){
                       svg.select("#tooltip").remove();
                      //svg.select(".tooltip").remove();
                      d3.select(this).attr("stroke","pink").attr("stroke-width",0.2);

                    });