d3.js实现鼠标悬停时指定节点文本添加下划线效果
D3.js 节点悬停文本下划线效果实现方案
原代码失效的核心原因
- d3的
.on()事件绑定方法必须传入事件回调函数作为第二个参数,原写法没有传入回调,样式修改逻辑不会在事件触发时执行 - 你将事件绑定在
<g>容器元素上,text-decoration是文本专属样式,需要作用在<g>下的<text>子节点才会生效,直接给<g>设置样式无法作用到内部文本上
正确实现代码
基础实现(所有节点都触发)
先给nodeEnter绑定正确的事件回调,在回调中选中当前节点下的文本元素修改样式即可:
var nodeEnter = node.enter().append("g") .attr("class", "node") .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; }) .on("click", click) .on("dblclick", dblclick) // 新增悬停事件 .on("mouseover", function(event, d) { d3.select(this).select("text").style("text-decoration", "underline"); }) .on("mouseout", function(event, d) { d3.select(this).select("text").style("text-decoration", "none"); })
注:如果使用d3 v5及更早版本,回调函数参数顺序为(d, i, nodes),调整参数顺序即可正常运行
增加条件过滤(仅部分节点触发)
如果只需要符合指定条件的节点触发下划线效果,直接在回调函数中加判断即可,比如判断节点数据的enableHover属性为true时才生效:
.on("mouseover", function(event, d) { // 替换为你自己的业务判断条件即可 if (d.enableHover === true) { d3.select(this).select("text").style("text-decoration", "underline"); } }) .on("mouseout", function(event, d) { if (d.enableHover === true) { d3.select(this).select("text").style("text-decoration", "none"); } })
如果需要优化性能,也可以在绑定事件前就过滤节点,只给符合条件的节点绑定事件:
var nodeEnter = node.enter().append("g") .attr("class", "node") .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; }) .on("click", click) .on("dblclick", dblclick); // 仅给符合条件的节点绑定悬停事件 nodeEnter.filter(function(d) { return d.enableHover === true; // 替换为你的判断条件 }) .on("mouseover", function(event, d) { d3.select(this).select("text").style("text-decoration", "underline"); }) .on("mouseout", function(event, d) { d3.select(this).select("text").style("text-decoration", "none"); });
内容的提问来源于stack exchange,提问作者MaxyCar
相关产品推荐
相关产品推荐

