我目前正在使用css直接在悬停时更改切片的颜色,但我想改为影响标签的颜色。我无法使用d3语法弄清楚如何执行此操作,任何提示都将不胜感激。 谢谢!
var arcs = vis.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice")
;
arcs.append("svg:path")
.attr("fill", function(d){
console.log(d.data.label, " ", (d.endAngle - d.startAngle))
if(d.endAngle - d.startAngle > .24){
return "#00C189"
} else {
return "#E3594B"
}
})
.attr("d", arc)
.on('click', function(d){ getRSS(d.data.label); })
.on('mouseover', function(d) {
// CHANGE LABEL COLOR HERE
})
.on('mouseout', function(d){
// CHANGE LABEL COLOR BACK HERE
});
arcs.filter(function(d) { return d.endAngle - d.startAngle > .2; }).append("svg:text")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.attr("transform", function(d) { //set the label's origin to the center of the arc
d.outerRadius = outerRadius; // Set Outer Coordinate
d.innerRadius = outerRadius*.3; // Set Inner Coordinate
return "translate(" + arc.centroid(d) + ")rotate(" + angle(d) + ")";
})
.style("fill", "White")
.text(function(d) { return d.data.label; })
;
答案 0 :(得分:4)
试试这段代码:
arcs.on("mouseover", function() {
d3.select(this)
.select("text")
.style("fill", "green");
}).on("mouseout", function() {
d3.select(this)
.select("text")
.style("fill", "black");
});
<强>演示:强>
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var labelArc = d3.svg.arc()
.outerRadius(radius - 40)
.innerRadius(radius - 40);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) {
return d.population;
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var data = [{
"age": "<5",
"population": 2704659
}, {
"age": "5-13",
"population": 4499890
}, {
"age": "14-17",
"population": 2159981
}, {
"age": "18-24",
"population": 3853788
}, {
"age": "25-44",
"population": 14106543
}, {
"age": "45-64",
"population": 8819342
}, {
"age": "≥65",
"population": 612463
}];
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) {
return color(d.data.age);
});
g.append("text")
.attr("transform", function(d) {
return "translate(" + labelArc.centroid(d) + ")";
})
.attr("dy", ".35em")
.text(function(d) {
return d.data.age;
});
g.on("mouseover", function() {
d3.select(this)
.select("text")
.style("fill", "green");
}).on("mouseout", function() {
d3.select(this)
.select("text")
.style("fill", "black");
});
function type(d) {
d.population = +d.population;
return d;
}
&#13;
.arc text {
font: 10px sans-serif;
text-anchor: middle;
}
.arc path {
stroke: #fff;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;