ECharts 提示框(tooltip)居中显示位置的设置技巧

在使用 ECharts 开发可视化图表时,默认的 tooltip 会显示在鼠标右侧。这种默认行为在某些布局中可能会导致遮挡、偏移或视觉不居中。为了让用户获得更优的交互体验,我们可以通过手动设置 tooltip.position 函数,实现 提示框在鼠标下方居中显示 的效果。

1、 默认问题

ECharts 默认的 tooltip 会显示在鼠标右边,如果鼠标靠近图表右侧边缘时,tooltip 可能会:

  • 超出图表边界

  • 遮挡关键信息

  • 视觉不对称、不美观

2、 设置 tooltip.position

tooltip: {
  trigger: 'item',
  formatter: '{b}: {c} ({d}%)',
  position: function (point, params, dom, rect, size) {
    const tooltipWidth = dom.offsetWidth || 100;
    const tooltipHeight = dom.offsetHeight || 40;
    const [x, y] = point;

    // 横向居中,纵向稍下
    return [x - tooltipWidth / 2, y + 10];
  },
  backgroundColor: 'rgba(0,0,0,0.7)',
  textStyle: {
    color: '#fff',
    fontSize: 12,
  },
}
参数 含义说明
point 当前鼠标的像素坐标 [x, y]
params tooltip 对应的数据项信息
dom tooltip 的 DOM 节点对象,可以读取其宽高
rect 触发该 tooltip 的图形的边界信息
size 当前图表的宽高等信息

 3、核心定位逻辑

const [x, y] = point;
const tooltipWidth = dom.offsetWidth || 100;
return [x - tooltipWidth / 2, y + 10];

解释:

  • x - tooltipWidth / 2: 让 tooltip 横向居中

  • y + 10: 将 tooltip 垂直放在鼠标下方 10 像素位置

 4、如果想显示在鼠标上方怎么办?

 

return [x - tooltipWidth / 2, y - tooltipHeight - 10];

 

你可能感兴趣的:(echarts,echarts,前端,javascript)