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

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

Selecting a single element in D3 .join

问题

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

settings.g.selectAll("node")
    .data(positions)
    .join(
        enter => {
            let point = enter.append("circle")
                .attr("cx", d => d.x)
                .attr("cy", d => d.y)
                .attr("stroke-opacity", 0.5)
                .on('mouseover', (d) => {
                    pointMouseOver(d)
                    point.attr("stroke-opacity", 1) //这会选择所有点,而不仅仅是一个
                })
                .on('mouseout', (d) => pointMouseOut(d))
        }
    )
英文:

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:

settings.g.selectAll("node")
            .data(positions)
            .join(
                enter => {
                    let point=enter.append("circle")
                    .attr("cx", d => d.x)
                    .attr("cy", d => d.y)           
                    .attr("stroke-opacity", 0.5)
                    .on('mouseover', (d)=> {
                        pointMouseOver(d)
                        point.attr("stroke-opacity", 1) //THIS SELECTS ALL POINTS, NOT JUST 1
                    })
                    .on('mouseout',  (d)=>pointMouseOut(d))
                    
                }
            )

答案1

得分: 1

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

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

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

在最近版本的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:

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

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:

确定