You need to enable JavaScript to run this app. 如何使用d3的join方法为柱状图添加悬停改色、点击删除等交互功能
优惠活动
大模型
产品
解决方案
定价
更多

如何使用d3的join方法为柱状图添加悬停改色、点击删除等交互功能

D3.js 基于join方法实现柱状图交互的实现方案
  • 悬停变色:直接在enter阶段给新增的柱子绑定鼠标事件即可,仅会对新增元素生效,不会重复绑定
  • 点击删除:需要将绘图逻辑抽离为接收数据参数的可复用函数,点击时过滤数据后重新调用渲染,join会自动匹配数据完成DOM的增删更新

完整修改代码

// 抽离渲染逻辑,入参为当前要渲染的最新数据
function renderChart(data) {
  rectG
    .selectAll('rect')
    // 第二个参数为数据唯一标识,避免join匹配DOM时出现错位
    .data(data, d => d.country)
    .join(
      (enter) =>
        enter
          .append('rect')
          .attr('width', xScale.bandwidth())
          .attr('height', 0)
          .attr('y', (d) => innerDimensions.height)
          .attr('x', (d) => xScale(d.country))
          .attr('fill', 'steelblue')
          .attr('stroke', 'black')
          .attr('stroke-width', 2)
          // 鼠标悬停改色
          .on('mouseenter', function() {
            d3.select(this).attr('fill', 'darkorange')
          })
          // 鼠标离开恢复原色
          .on('mouseleave', function() {
            d3.select(this).attr('fill', 'steelblue')
          })
          // 点击删除当前柱子
          .on('click', function(event, d) {
            // 过滤掉当前点击对应的数据项
            const filteredData = data.filter(item => item.country !== d.country)
            // 用新数据重新渲染
            renderChart(filteredData)
          })
          .call((enter) =>
            enter
              .transition()
              .duration(1000)
              .attr('y', (d) => yScale(d.population))
              .attr(
                'height',
                (d) => innerDimensions.height - yScale(d.population)
              )
          ),
      (update) => update.attr('fill', 'orange'),
      // 可选:给删除的柱子添加退场动画
      (exit) => exit
        .transition()
        .duration(300)
        .attr('height', 0)
        .attr('y', innerDimensions.height)
        .remove()
    );
}

// 首次渲染调用,initialData为你的原始数据集
renderChart(initialData)

注意事项

  • 事件绑定不要用箭头函数,否则this不会指向当前触发事件的柱子DOM元素,无法正确选中目标元素修改样式
  • 必须给data()方法传入第二个参数作为数据的唯一键,否则删除数据时join可能会错误匹配DOM,导致显示异常
  • 可以自行修改悬停的颜色值、退场动画的时长和效果,匹配你的项目设计需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 17:24:04