如何将href应用于整个svg?

时间:2018-09-05 19:49:15

标签: javascript d3.js svg href

我有一个页面可以构建一堆饼图。在每个页面上,我要向页面上的另一个位置添加href。

当前我的代码可以使用,但是它仅将href应用于饼形图的各个部分以及文本。因此,例如,如果单击饼图的圆环,它将按应有的方式工作,但是如果单击圆环之间的 空间,则不会。

SVG本身更大,更易于单击,但是即使我将shang标签附加到svg,它也仅适用于SVG中的 元素。我该如何纠正这种行为?

function pieChartBuilder(teamName, values) {
    var dataset = values;

    var trimTitle = teamName.replace(' ', '');
    trimTitle = trimTitle.toLowerCase();

    var width = 175,
        height = 175,
        cwidth = 8;

    var color = d3.scale.category20();

    var pie = d3.layout.pie()
        .sort(null);

    var arc = d3.svg.arc();

    var svg = d3.select("#pieChart").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("a") // here is where I append the anchor tag to the SVG, but it only applies to the individual elements within.
        .attr("href", ("#" + trimTitle))
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")

    var gs = svg.selectAll("g").data(d3.values(dataset)).enter().append("g");
    var path = gs.selectAll("path")
        .data(function (d) { return pie(d); })
        .enter().append("path")
        .attr("fill", function (d, i) { return color(i); })
        .attr("d", function (d, i, j) { return arc.innerRadius(5 + cwidth * j).outerRadius(3 + cwidth * (j + 1))(d); });

    svg.append("text")
        .attr("class", "title")
        .attr("x", 0)
        .attr("y", (0 - (height / 2.5)))
        .attr("text-anchor", "middle")
        .style("fill", "#808080")
        .text(teamName);

}

1 个答案:

答案 0 :(得分:1)

我认为您选择器的选择方法错误。您想在svg标记内添加a吗?

d3.select("#pieChart")
  .append("a")
  .append("svg");

您(1)选择pieChart,然后(2)向其附加一个a标签,然后您(3)向其附加svg

相关问题