echarts踩坑记录

436 阅读1分钟

背景: 点击echarts表格数据区域触发事件,生成弹窗,可以用echart官方提供的on监听,但是当图表中的折线或者点很小的时候,鼠标可能会点不到从而无法触发这个事件,像这样

a6a611c6950d6937bf4b0c511dddef1.jpg

这个时候可以用echarts提供的getZr()函数,官方文档上好像也没有这个函数的详细说明

myChart.getZr().on("click", (params) => {
    // 获取点击点的像素坐标点
    const pointInPixel = [params.offsetX, params.offsetY]
    
    // 转换为逻辑坐标点
    const pointInGrid = myChart.value.convertFromPixel({ seriesIndex: 0 }, pointInPixel)
    
    // 这里的zIndex就相当于直接使用on监听的dataIndex
    const zIndex = pointInGrid[0]
 })

那么怎么能知道点击的区域有没有数据呢,可以通过params参数里的属性target和topTarget来判断

//点击的区域没有数据
{
    target => undefined  
    topTarget => object
}

//点击的区域有数据
{
    target => object  
    topTarget => object
}