[echarts] click event of histogram

insert image description here
Let's start with a concise code for writing echarts charts:

// 这样获取echarts的dom节点是因为:如果将柱状图封装成了一个组件,在一个页面中多次使用,若还是按常规获取dom节点,会报一个警告
let charts = echarts.getInstanceByDom(
  document.getElementById(props.id)
)
if (charts == null) {
    
    
  charts = echarts.init(document.getElementById(props.id))
}
charts.clear()
let option = {
    
    
	...
}
charts.resize()
charts.setOption(option)

As shown in the figure, if the histogram needs to have a click event: But only when the blue column part is clicked will the click event be triggered

myChart.on('click', function (params) {
    
    
	console.log(params)
})

If the column has no data, it will not be triggered when clicked with the above method. If there is no data to click the background and still want to trigger the click event, use the following method:

charts.getZr().off('click')		// 先取消点击,再触发,免得造成连续抖动触发
charts.getZr().on('click', function (params) {
    
    
	// 这个部分照抄,你想通过点击拿到的当前柱条的数据,都可以在下面这些属性中拿到,如果我注释没有你想要的,需要console一下charts.getOption()查找对应的属性名
    let pointInPixel = [params.offsetX, params.offsetY];
    
    if (charts.containPixel('grid', pointInPixel)) {
    
    
      let pointInGrid = charts.convertFromPixel({
    
    
        seriesIndex: 0
      }, pointInPixel);
      
      let xIndex = pointInGrid[1]; 			// 索引
      
      let handleIndex = Number(xIndex);
      
      let seriesObj = charts.getOption(); 	// 图表object对象
      
      let op = charts.getOption();
      
      //获得图表中点击的列
      let dataY = op.yAxis[0].data[handleIndex];  			//获取点击的列名
      
      let dataX = seriesObj.series[0].data[handleIndex]   	// 获取当前点击的柱条的数值 

		... // 写获取到当前点击需要的数值后的操作   
    }
})

In addition, let me add the writing method of crossing and crossing events. The attributes are the same, that is, the event name is unique: , mousemove mouseoutthese two correspond to each other, so it must be written in this way, other writing may be invalid

// 划过
charts.getZr().off('mousemove');
charts.getZr().on('mousemove', function(params) {
    
    

})
// 划出
charts.getZr().off('mouseout');
charts.getZr().on('mouseout', function(params) {
    
    

})

Guess you like

Origin blog.csdn.net/bbt953/article/details/127846771