Echarts柱状图点击事件点击阴影也会有点击效果

1,676 阅读1分钟

柱状图当我们给每一个加点击事件时,只会给我们的柱子添加上点击事件,但是有时候数据为零,就无法触发这个点击事件,所以最好是给鼠标移上去的阴影加点击事件。这个时候需要用到Echarts新增的方法 getZr()合并containPixel()扩大点击范围。代码如下:

首先我们可以先封装一个事件以便于所有的柱状图使用:

//dom为Echart渲染的dom元素
//callback为图表那边传过来的操作回调函数
export function areaClick(dom, callback) {
if (!dom) return new Error("Please pass in the dom structure");
//getZr()事件获取柱状图当前点击列的数据
dom.getZr().on("click", (params) => {
    const pointInPixel = [params.offsetX, params.offsetY];
    //containPixel()扩大点击范围
    if (dom.containPixel("grid", pointInPixel)) {
        let xIndex = dom.convertFromPixel({ seriesIndex: 0 }, [
            params.offsetX,
            params.offsetY
        ])[0];
        //获取到图表的配置项
        var op = dom.getOption();
        const xAxis = op.xAxis;
        const yAxis = op.yAxis;
        const series = op.series;
        let result = {
            xAxis,
            yAxis,
            series
        };
        callback({ result, clickIndex: xIndex });
    }
 });
}

首先import引入封装的函数 然后在表格options中调用这个函数。代码实例如下

     //图标调用配置项
     that.redWarningDistribution.setOption(option);
       areaClick(that.redWarningDistribution, (obj) => {
        // console.log("kkk",obj);
            const index = obj.clickIndex;
            const name = obj.result.xAxis[0].data[index];
            //弹窗打开
          that.openhsyqfbModal(obj, name);
        });