D3图例自定义checkbox点击添加勾选标记功能失效问题求助
D3 自定义图例Checkbox交互问题修复
核心问题原因
- ID选择器语法错误:
d3.select()选择ID元素时需要加#前缀,直接传入d.target.id无法匹配到对应元素 - SVG元素嵌套错误:
<rect>是自闭合元素,内部不能嵌套<text>元素,给rect追加text会被浏览器自动拦截无法渲染 - 类名设置方法错误:
attr("classed", "checked")是错误写法,d3中设置类名可使用.classed("checked", true)方法或者.attr("class", "checked")属性赋值 - 重复元素问题:每次点击都新增text元素,多次点击会出现文字重叠,没有提前清理已存在的勾选标记
修正后代码
初始化Checkbox部分
legend.append("g") .classed("checkbox-group", true) // 给外层g加类名方便选择 .append("rect") .classed("checkbox", true) .attr("x", width + 10) .attr("height", 18) .attr("width", 18) .attr("stroke", "#000000") .attr("stroke-width", "1") .attr("fill", "#ffffff00") .attr("checked", "false") .attr("id", function (d) { return "c" + valueColumns.indexOf(d); })
点击回调函数部分
function mouseclick(d) { const targetId = d.target.id; // 先清空所有已有的勾选标记 d3.selectAll(".checked").remove(); // 给选中的checkbox所属的外层g添加text d3.select(`#${targetId}`) .node() // 获取原生DOM节点 .parentNode // 取外层的g元素 .append("text") .attr("x", width + 10) .attr("dy", "0.65em") .attr("dx", "0.65em") .attr("alignment-baseline", "middle") .attr("font-size", 24) .style("fill", "#000000") .attr("id", function () { return valueColumns.indexOf(d); }) .classed("checked", true) // 正确设置类名 .text("x"); // 替换为你需要的勾选标记x }
内容的提问来源于stack exchange,提问作者Zehke
相关产品推荐
相关产品推荐

