gpt4 book ai didi

javascript - 在 D3 v6 中无法在鼠标悬停时获取节点基准

转载 作者:行者123 更新时间:2023-12-01 16:09:43 25 4
gpt4 key购买 nike

我正在尝试使用 selection.on() 获取节点的绑定(bind)数据。在 D3 v6 中。在我的事件监听器中,我得到的是鼠标事件数据而不是数据。我如何获得数据?
这是我的代码

const data = {
"nodes": [{
"id": "Myriel",
"group": 1
}, {
"id": "Napoleon",
"group": 1
}]};

const nodes = data.nodes.map(d => Object.create(d));

const node = svg.append("g")
.selectAll("circle")
.data(nodes)
.join("circle")
...

node.on("mouseover",d=>{
console.log(d); //output = MouseEvent
console.log(d.id); //output = undefined
});

最佳答案

D3v5 及更早版本
在 d3v5 和更早的版本中,我们可以使用该模式:

selection.on("eventType", function(d,i,nodes) { .... })
在哪里 d是触发事件的元素的数据, i是它的索引, nodes当前的元素组。可以使用 d3.event 在事件监听器中访问事件信息.
D3v6
在 d3v6 中,模式已更改:
selection.on("eventType", function(event, d) { .... })
现在事件作为第一个参数直接传递给监听器,数据现在是传递给监听器的第二个参数。作为此更改的一部分 d3.event已被删除。
如文档中所述:

D3 now passes events directly to listeners, replacing the d3.event global and bringing D3 inline with vanilla JavaScript and most other frameworks. (source)


此更改适用于 brush.on , transition.on , 和 drag.on , zoom.on以及 selection.on .
这个
您仍然可以使用 d3.select(this)在事件监听器函数中,就像您在 d3v6 之前所做的那样。但是,如果使用箭头函数, this会有不同的范围。在 d3v5 及更早版本中,您可以使用:
(d,i,nodes) => d3.select(nodes[i])...
在 d3v6+ 中,您可以使用(对于 selection.on() ):
(event,d) => d3.select(event.currentTarget)...
定位
要获得触发事件的 x,y 位置,您可以使用 d3.mouse(this) ,您现在可以使用:
d3.pointer(event);
您会在哪里使用 d3.event.xd3.event.y ,在 d3v5 中,您现在可以使用:
event.x, event.y
示例
下面是将事件和数据传递给 D3v6 中的监听器函数的简单示例。该片段使用 d3.pointer() 来获取点击相对于 SVG 的 x,y 属性。单击矩形以获取矩形的基准以及记录到控制台的事件的 x 和 y 属性:

var svg = d3.select("body")
.append("svg");

svg.selectAll("rect")
.data([1,2,3])
.enter()
.append("rect")
.attr("width",30)
.attr("height",30)
.attr("x", function(d) { return d*50; })
.on("click", function(event, d) {
console.log(d);
console.log(d3.pointer(event));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.0.0/d3.min.js"></script>

i 呢?和 nodes ?
索引和节点组不再传递给事件监听器函数。但是,迁移指南确实提供了如何查找当前节点组和索引 here 的示例。 .

关于javascript - 在 D3 v6 中无法在鼠标悬停时获取节点基准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63693132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com