用d3.js将div添加到圆形上

4

我有一个使用d3.js创建的甜甜圈图表,我希望在其中心放置一些信息。虽然我可以添加文本元素,但我想要放置格式化的信息,因此我决定在鼠标悬停时添加div:

$(".arc").on("mouseover",(function(){
d3.select("text").remove();
var appendingString="<tspan>"+cityName[$(this).attr("id")]+"</tspan> <tspan>"+$(this).attr("id")+"%</tspan>";
group
.append("text")
.attr("x",-30)
.attr("y",-10)
.text(appendingString);
})); 

由于某些原因,div被成功添加了我需要的信息,但没有显示出来。添加它的正确方式是什么,或者有其他替代方法吗? 完整脚本如下:

<script>
var cityNames=["Челябинск","Область","Миасс","Копейск"];
var cityPercentage=[50,30,20,10];
var width=300,
    height=300,
    radius=100;
var color=d3.scale.linear()
            .domain([0,60])
            .range(["red","blue"]);
var cityDivision = d3.select("#cities")
            .append("svg")
            .attr("width", width)
            .attr("height", height)
            .attr("class","span4");
var group=cityDivision.append("g")
.attr("transform","translate(" + width / 2 + "," + height / 2 + ")");
var arc=d3.svg.arc()
    .innerRadius(radius-19)
    .outerRadius(radius);
var pie= d3.layout.pie()
    .value(function(d){return d;});
var cityName={
    50:"Челябинск",
    30:"Область",
    20:"Миасс",
    10:"Копейск"
}
var arcs=group.selectAll(".arc")
    .data(pie(cityPercentage))
    .enter()
    .append("g")
    .attr("class","arc")
    .attr("id",function(d){return d.data;});
    arcs.append("path")
    .attr("d",arc)
    .attr("fill",function(d){return color(d.data);});
//Добавление надписи в центре
    group
    .append("circle")
    .style("fill","white")
    .attr("r",radius-20);
$(".arc").on("mouseover",(function(){
    d3.select("div.label").remove();
    var appendingString=cityName[$(this).attr("id")]+"\n "+$(this).attr("id")+"%";
    group
    .append("div")
    .attr("class","label")
    .html(appendingString);
}));
</script>
1个回答

6
您不能直接将`div`注入到`svg`元素中。这里有两个选项:
  1. 使用一个`text`元素,然后在其中使用`
  2. 使用一个`foreignObject`元素,然后在其中包含格式化的HTML(即`div`)。对于此的浏览器支持相当不稳定: https://dev59.com/MG445IYBdhLWcg3wM3bx#4992988

这里是在此情况下使用`tspan`的示例:
$(".arc").on("mouseover",(function(){
    d3.select("text").remove();
    var text = group
    .append("text")
    .attr("x",-30)
    .attr("y",-10)
    .selectAll('tspan')
    .data([cityName[$(this).attr('id')], $(this).attr('id') + '%'])
    .enter()
    .append('tspan')
      .attr('x', 0)
      .attr('dx', '-1em')
      .attr('dy', function (d, i) { return (2 * i - 1) + 'em'; })
      .text(String);

})); 

附注:看起来你正在使用数字([0-9]*)作为id属性。有效的id属性不能以数字开头,尽管它们在大多数浏览器中可以工作。


现在就像你建议的那样,但它不是两行,而是类似于<tspan>...</tspan><tspan>...</tspan>。 - Sergey Scopin
@SergeyScopin已经更新了答案,并附上了一个示例。它应该能给你一个在text内使用tspan的一般想法。 - musically_ut

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接