在mouseover事件处理程序中使用多个函数时出现问题



我正在使用d3v5,目前正试图制作力定向图的一个节点:

  1. 淡出未直接连接到"mouse-over'ed"节点的节点
  2. 放大手头的节点

到目前为止,我已经管理了前者,但我无法管理任何与fade()函数一起触发的函数。考虑:

var node = svg
.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter()
.append("circle")
.attr("r", function (d) {
return 1.5 * Math.sqrt(d.weight);
})
.attr("fill", function (d) {
return "red";
})
.call(
d3
.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
)
.on("mouseover", fade(0.2))
.on("mouseout", fade(1));

以及"淡入淡出"功能:

function fade(opacity) {
return function (d) {
// check all other nodes to see if they're connected
// to this one. if so, keep the opacity at 1, otherwise
// fade
node.style("stroke-opacity", function (o) {
thisOpacity = isConnected(d, o) ? 1 : opacity;
return thisOpacity;
});
node.style("fill-opacity", function (o) {
thisOpacity = isConnected(d, o) ? 1 : opacity;
return thisOpacity;
});
// also style link accordingly
link.style("stroke-opacity", function (o) {
return o.source.name === d.name || o.target.name === d.name
? 1
: opacity;
});
text.style("fill-opacity", function (o) {
thisOpacity = isConnected(d, o) ? 1 : opacity;
return thisOpacity;
});
};
}

到目前为止,一切都按预期进行。然而,当我开始四处寻找在mouseover(和mouseout(上执行另一个函数时,我尝试了传统的方法,如下所示:

var node = svg
//...
.on("mouseover", function (d) {
console.log("make node bigger")
fade(0.2);
})
.on("mouseout", function (d) {
console.log("make node smaller")
fade(1);
});

输出两条控制台消息,但不执行fade()功能。我试着放return fade(...);,但没有用。

我很想知道为什么会发生这种事。非常感谢。

当你做…

.on("mouseover", fade(0.2))

您立即调用fade,并返回其返回值,它本身就是一个函数:

return function (d) { //etc...

您看到的d参数对应于selection.on()方法传递的第一个参数。最后,您所拥有的只是一个惯用的D3侦听器,它是一个接受数据作为第一个参数的匿名函数。

然而,现在你正在这么做。。。

.on("mouseover", function (d) {
console.log("make node bigger")
fade(0.2);
}) 

您必须重构fade函数,因为数据不再作为参数传递。最简单的方法是将数据作为参数传递:

.on("mouseover", function (d) {
console.log("make node bigger")
fade(d, 0.2);
//   ^---- datum here
}) 

然后,在fade中,为基准添加一个参数,并删除return function(d)部分:

function fade(d, opacity) {
//datum---^
node.style("stroke-opacity", function (o) {
thisOpacity = isConnected(d, o) ? 1 : opacity;
return thisOpacity;
});
//etc...
}

fade()中,替换:

node.style("stroke-opacity", function (o) {
thisOpacity = isConnected(d, o) ? 1 : opacity;
return thisOpacity;
});

带有:

node.style("opacity", function (o) {
thisOpacity = isConnected(d, o) ? 1 : opacity;
return thisOpacity;
});

最新更新