You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在D3.js的.join()方法中如何选中单个元素?

问题原因与解决办法

你代码里的point变量是所有新创建的circle元素组成的选择集,所以在mouseover事件里调用point.attr()会修改所有点的样式,而不是当前鼠标悬停的那个点。

解决办法有两种:

方法一:用普通函数+this指代当前元素

把事件处理函数改成普通函数(不要用箭头函数),此时this会指向触发事件的单个circle元素,再用d3.select()选中它:

settings.g.selectAll("node")
            .data(positions)
            .join(
                enter => {
                    enter.append("circle")
                    .attr("cx", d => d.x)
                    .attr("cy", d => d.y)           
                    .attr("stroke-opacity", 0.5)
                    .on('mouseover', function(d) { // 这里用普通函数
                        pointMouseOver(d)
                        d3.select(this).attr("stroke-opacity", 1) // 仅修改当前点
                    })
                    .on('mouseout',  (d) => pointMouseOut(d))
                    
                }
            )

方法二:箭头函数+d3.event.currentTarget

如果一定要用箭头函数,因为箭头函数没有自己的this,可以通过d3.event.currentTarget获取当前触发事件的DOM元素:

settings.g.selectAll("node")
            .data(positions)
            .join(
                enter => {
                    enter.append("circle")
                    .attr("cx", d => d.x)
                    .attr("cy", d => d.y)           
                    .attr("stroke-opacity", 0.5)
                    .on('mouseover', (d) => {
                        pointMouseOver(d)
                        d3.select(d3.event.currentTarget).attr("stroke-opacity", 1) // 选中当前点
                    })
                    .on('mouseout',  (d) => pointMouseOut(d))
                    
                }
            )

内容的提问来源于stack exchange,提问作者Tania

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 22:52:03