Chart.js折线图悬停null值点位时如何隐藏tooltip
问题根因
Chart.js 3.x 版本下,使用 mode: 'nearest' + axis: 'x' 交互规则时,会自动过滤值为 null 的数据点,直接匹配同x坐标下其他数据集的最近有效点。此时tooltip回调拿到的上下文里不包含第一个数据集的null点信息,常规的null值判断拦截逻辑无法触发,最终出现悬停null点位置时tooltip跳转至第二个数据集点位的异常。
修复方案
调整交互匹配逻辑为按x轴索引匹配,同时增加tooltip显隐兜底判断:当当前x索引对应的第一个数据集值为null时,直接隐藏tooltip。完整可用配置如下:
const options = { interaction: { intersect: false, mode: 'index' // 替换原nearest模式,按x轴索引匹配所有同列点位 }, maintainAspectRatio: true, animation: false, plugins: { tooltip: { mode: 'index', axis: 'x', position: 'average', yAlign: "bottom", // 过滤所有null值点位 filter: (tooltipItem) => { const raw = tooltipItem.raw; return raw !== null && raw?.y !== null; }, // 兜底显隐控制 enabled: (context) => { const points = context.tooltip.dataPoints; if (!points?.length) return false; const idx = points[0].dataIndex; const firstDatasetPoint = context.chart.data.datasets[0].data[idx]; // 第一个数据集当前x位置为null时直接隐藏tooltip if (firstDatasetPoint === null || firstDatasetPoint?.y === null) { return false; } return true; } }, }, scales: { y: { type: 'linear', beginAtZero: true, min: 0, grace: '20%', } }, chartArea: { backgroundColor: "rgb(240,240,240)" }, // 可选配置:折线在null点位处断开,视觉上明确无数据区间 elements: { line: { spanGaps: false } } }
异常表现截图

内容的提问来源于stack exchange,提问作者sinootz
相关产品推荐
相关产品推荐

