html - D3 在鼠标悬停时填充饼图段

标签 html css d3.js tooltip mouseover

我有一个这样定义的饼图:

var pie = d3.pie()
    .sort(null)
    .value(function(d) { return +d.value; });

var path = d3.arc()
    .outerRadius(radius - 10)
    .innerRadius(0.65*radius);

var arc = g.selectAll(".arc")
    .data(pie(data))
    .enter()
    .append("g")
    .attr("class", "arc")

arc.append("path")
    .attr("d", path)
    .attr("fill", function(d, i) { return colours[i]; }) //Everything up to here works
    .on('mouseover', function() {console.log('over'); arc.style("fill","red");});

最后一行只工作了一半 - 控制台确实打印“结束”,但该段没有改变颜色。这是错误的做法吗?

最佳答案

您应该使用 d3.select(this) 而不是 arc 选择当前悬停的元素:

// .on('mouseover', function() { arc.style("fill","red"); });
.on('mouseover', function() { d3.select(this).style("fill","red"); });

这是一个演示:

var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

var g = svg.append("g").attr("transform", "translate(100,100)")

var data = [
  { value: 4 }, { value: 12 }
];
var colours = ["green", "blue"];
var radius = 25;

var pie = d3.pie()
    .sort(null)
    .value(function(d) { return +d.value; });

var path = d3.arc()
    .outerRadius(radius - 10)
    .innerRadius(0.65*radius);

var arc = g.selectAll(".arc")
    .data(pie(data))
    .enter()
    .append("g")
    .attr("class", "arc")

arc.append("path")
    .attr("d", path)
    .attr("fill", function(d, i) { return colours[i]; }) //Everything up to here works
    // .on('mouseover', function() { console.log('over'); arc.style("fill","red"); });
    .on('mouseover', function() { console.log('over'); d3.select(this).style("fill","red"); });
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>

关于html - D3 在鼠标悬停时填充饼图段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50190526/

相关文章:

javascript - 嵌套到另一个函数中的 Fancybox 函数不起作用

html - 字体在 Chrome 和 Firefox 中显示不同

jquery - 如何使 Bootstrap 警告框出现在按钮下方

html - CSS - 如何编码流畅的 DIV 列,以响应 Bootstrap 3 的显示变化?

javascript - dc.js - 如何获取数据集中列的平均值

javascript - 使用在 AngularJS 中动态构建的表中的输入验证行

javascript - 仅使用 HTML 和 JavaScript 显示更多/更少文本

CSS 自动完成字体大小

javascript - 如何在 d3 V3 中使用定时器?

javascript - d3 - 无法将选择/选项下拉列表添加到 svg-g 元素