我使用this blocks示例制作饼图,以便在鼠标悬停时增加饼图切片。除了补间之外,我还想让饼切片改变颜色并有一个工具提示,所以我想要另一个叫做d和i的函数。
问题在于虽然arcTween函数的工作方式与鼠标悬停相同,但如果它包含在另一个函数中则不起作用 - 我想这样做,以便我可以访问工具提示的索引。
有人可以向我解释为什么这不起作用吗?我已经尝试了很多方法来返回具有不同变量的函数,并且无法使其正常工作。
完整代码:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
stroke: #333;
fill-opacity: 90%;
stroke-width: 1.5px;
transition: fill 250ms linear;
transition-delay: 150ms;
}
path:hover {
stroke: #000;
fill-opacity: 100%;
transition-delay: 0;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var data = [44, 16, 9, 8,8,8,4,3];
function findColor(index){
var colors = [
"#cb5b49",
"#8bbbd3",
"#1f61a3",
"#c7dae4",
"#f0d0bd",
"#e89d7b",
"#a91729",
"#408cb9"];
return colors[index];
}
var width = 960,
height = 500;
var outerRadius = height / 2 - 20,
cornerRadius = 10;
var pie = d3.layout.pie();
var arc = d3.svg.arc()
.padRadius(outerRadius);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
svg.selectAll("path")
.data(pie(data))
.enter().append("path")
.each(function(d) { d.outerRadius = outerRadius - 20; })
.attr("d", arc)
.attr("fill",function(d, i){return findColor(i)})
.on("mouseover", arcTween(outerRadius + 20, 0)) //THIS WORKS
//THE BELOW DOES NOT WORK FOR SOME REASON
// .on("mouseover", function(d,i){console.log(i); return arcTween(outerRadius + 20, 0);})
.on("mouseout", arcTween(outerRadius - 20, 150));
function arcTween(outerRadius, delay) {
return function() {
d3.select(this).transition().delay(delay).attrTween("d", function(d) {
var i = d3.interpolate(d.outerRadius, outerRadius);
return function(t) { d.outerRadius = i(t); return arc(d); };
});
};
}
</script>
答案 0 :(得分:2)
Per @LarsKotthoff,你需要这个来修复:jsfiddle.net/vndrw57a
svg.selectAll("path")
.data(pie(data))
.enter().append("path")
.each(function(d) { d.outerRadius = outerRadius - 20; })
.attr("d", arc)
.attr("fill",function(d, i){return findColor(i)})
.on("mouseover", function(){ arcTween(outerRadius + 20, 0, this)(); })
.on("mouseout", arcTween(outerRadius - 20, 150));
function arcTween(outerRadius, delay, that) {
return function() {
var el = (that !== undefined ? that : this);
d3.select(el).transition().delay(delay).attrTween("d", function(d) {
var i = d3.interpolate(d.outerRadius, outerRadius);
return function(t) { d.outerRadius = i(t); return arc(d); };
});
};
答案 1 :(得分:0)
代码
function(d,i){console.log(i); return arcTween(outerRadius + 20, 0);})
返回一个函数(arcTween
的返回值),它不会执行该函数。您可以通过添加()
function(d,i){console.log(i); arcTween(outerRadius + 20, 0)();})