我有一个如下定义的饼图:
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");});
最后一行只有一半工作 - 控制台确实打印了#39;但该段不会改变颜色。这是错误的做法吗?
答案 0 :(得分:1)
您应该使用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>
&#13;