鼠标悬停时在sunburst中间添加标签

时间:2015-05-09 14:35:54

标签: javascript css d3.js

我一直致力于通过以下链接http://bl.ocks.org/mbostock/4063423提供的旭日形象可视化示例。我希望标签显示已被鼠标悬停的分区的名称。现在,每当我将鼠标悬停在一个分区上时,它就会显示" flare"只在中间。有没有办法让我访问孩子的名字?

d3.json("flare.json", function(error, root) {
var path = svg.datum(root).selectAll("path")
.data(partition.nodes) //access the nodes
.enter()
.append("path")
.attr("display", function(d) { return d.depth ? null : 'none';}) //hide inner ring 
.attr("d", arc)//used whenever I come across a path 
.style("stroke", "#fff")
.style("fill", function(d) { return color((d.children ? d : d.parent).name);})
.style("fill-rule", "evenodd")
.each(stash)
.on("mouseover", mouseover)
.on("mouseout", mouseout);

var label = svg.append("text")
      .attr("id", "tooltip")
      .attr("x", 10)
      .attr("y", 50)
      .attr("text-anchor", "middle")
      .attr("font-family", "sans-serif")
      .attr("font-size", "11px")
      .attr("font-weight", "bold")
      .attr("fill", "black")
      .style("opacity", 0)
      .text(function(d) { return d.name; });

function mouseover(d) {

  d3.select(this)
        .transition()
        .duration(100)
        .style("opacity", 0.3);

label.style("opacity", .9); 


console.log('mouseover', mouseover);    
  };

function mouseout(d) {
d3.select(this)
        .transition()
        .duration(100)
        .style("opacity", 1);

        label.style("opacity", 0);

console.log('mouseout', mouseout);  
  };

1 个答案:

答案 0 :(得分:1)

通过首先将文本元素附加到g元素而不是svg元素来解决此问题。其次,你想在mousehandler之外创建一个具有特定id的文本元素,然后在事件处理程序中使用该Id调用它。就像这样。

d3.json("flare.json", function(error, root) {
var g = svg.selectAll("g")
  .data(partition.nodes(root))
.enter().append("g");

var path = 
        g.append("path")
        .attr("display", function(d) { return d.depth ? null : 'none';}) //hide inner ring 
        .attr("d", arc)//used whenever I come across a path 
        .attr("id", "part")
        .style("stroke", "#fff")
        .style("fill", function(d) { return color((d.children ? d : d.parent).name);})
        .style("fill-rule", "evenodd")
        .each(stash)
        .on("mouseover", mouseover)
        .on("mouseout", mouseout);

var text = g.selectAll("text")
            .data(partition.nodes(root))
            .enter()
            .append("text")
            .attr("id", "tip")
            .attr("x", 10)
            .attr("y", 50)
            .attr("font-size", "11px")
            .style("opacity", 0);


function mouseover(d) {

  d3.select(this)
        .transition()
        .duration(1000)
        .ease('elastic')
        .style("opacity", 0.3);

//label.style("opacity", .9);
d3.select("#tip").text(d.name).style("opacity", 0.9);

console.log('mouseover', mouseover);    
};

function mouseout(d) {
d3.select(this)
        .transition()
        .duration(100)
        .style("opacity", 1);

d3.select("#tip").text(d.name).style("opacity", 0);

console.log('mouseout', mouseout);  
  };