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

React Chart.js:如何禁用单个数据集的Tooltip交互

解决Chart.js多数据集折线图仅指定数据集触发Tooltip的问题

核心实现思路

  • 给不需要触发Tooltip的数据集设置不可交互的点属性,让Chart.js无法检测到光标交互
  • (可选)通过Tooltip的过滤函数,明确排除目标数据集

完整代码示例

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        datasets: [
            // 主数据集(可触发Tooltip)
            {
                label: '主数据',
                data: [12, 19, 3, 5, 2, 3],
                borderColor: '#2196F3',
                fill: false,
                tension: 0.1
            },
            // 虚线填充数据集(不触发Tooltip)
            {
                label: '填充虚线',
                data: [12, null, null, null, null, 3], // 仅首尾点
                borderColor: '#9E9E9E',
                borderDash: [5, 5],
                fill: true,
                backgroundColor: 'rgba(158, 158, 158, 0.1)',
                // 关键配置:让点无法被交互检测
                pointRadius: 0,
                pointHitRadius: 0,
                // 可选:禁用该数据集的所有交互
                hoverRadius: 0,
                hoverBackgroundColor: 'transparent'
            }
        ]
    },
    options: {
        // 可选:通过Tooltip过滤函数双重保障
        plugins: {
            tooltip: {
                filter: function(tooltipItem) {
                    // 只保留第一个数据集的Tooltip项(索引为0)
                    return tooltipItem.datasetIndex === 0;
                }
            }
        }
    }
});

关键配置说明

  • pointRadius: 0:隐藏第二个数据集的点,同时让Chart.js不识别该点的交互区域
  • pointHitRadius: 0:彻底禁用该数据集点的点击/悬停检测范围,确保光标靠近时不会触发
  • tooltip.filter:额外的过滤逻辑,即使有漏网的交互检测,也会直接排除第二个数据集的Tooltip内容

效果验证

  • 光标悬停主数据集的点时,正常显示Tooltip
  • 光标靠近虚线填充区域或其首尾点时,不会触发任何Tooltip

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:47:52