在D3中选择单个元素时,请使用 `.join`。

huangapple go评论93阅读模式
英文:

Selecting a single element in D3 .join

问题

我有以下的代码,它使用mouseover和mouseout函数创建一系列点。然而,我无法弄清楚如何引用单个“point”实例 - 使用变量point会选择所有点:

  1. settings.g.selectAll("node")
  2. .data(positions)
  3. .join(
  4. enter => {
  5. let point = enter.append("circle")
  6. .attr("cx", d => d.x)
  7. .attr("cy", d => d.y)
  8. .attr("stroke-opacity", 0.5)
  9. .on('mouseover', (d) => {
  10. pointMouseOver(d)
  11. point.attr("stroke-opacity", 1) //这会选择所有点,而不仅仅是一个
  12. })
  13. .on('mouseout', (d) => pointMouseOut(d))
  14. }
  15. )
英文:

I have the following code which creates a series of points with mouseover and mouseout functions. However, I cannot figure out how to reference a single "point" instance - using the variable point selects all of them:

  1. settings.g.selectAll("node")
  2. .data(positions)
  3. .join(
  4. enter => {
  5. let point=enter.append("circle")
  6. .attr("cx", d => d.x)
  7. .attr("cy", d => d.y)
  8. .attr("stroke-opacity", 0.5)
  9. .on('mouseover', (d)=> {
  10. pointMouseOver(d)
  11. point.attr("stroke-opacity", 1) //THIS SELECTS ALL POINTS, NOT JUST 1
  12. })
  13. .on('mouseout', (d)=>pointMouseOut(d))
  14. }
  15. )

答案1

得分: 1

point变量是输入选择, 在你的情况下包含多个元素。

要获取选定的元素,请使用this或者,因为你使用了箭头函数:

  1. .on('mouseover', (d, i, n) => {
  2. d3.select(n[i]).attr("stroke-opacity", 1)
  3. })

在最近版本的D3中,你可以在监听器中使用event.currentTarget.on('mouseover', (event, d) => { ... })

英文:

The point variable is the enter selection, which in your case contains several elements.

To get the selected element use this or, since you have an arrow function:

  1. .on('mouseover', (d, i, n)=> {
  2. d3.select(n[i]).attr("stroke-opacity", 1)
  3. })

In recent versions of D3 you can use event.currentTarget in the listener: .on('mouseover', (event, d) => { ... }).

huangapple
  • 本文由 发表于 2023年7月10日 14:57:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651335.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定