1 回答
TA贡献1866条经验 获得超5个赞
确实,点击栏外时无法接收到常见事件,但 Echarts 是成熟的框架,几乎任何事件都可以通过低级对象接收zRender。您需要访问zRenderwithgetZr()并将单击的像素的坐标转换为图表坐标。之后,您将拥有系列数据点的索引,通过它来获取类别将很容易。
myChart.getZr().on('click', params => {
var pointInPixel = [params.offsetX, params.offsetY];
var pointInGrid = myChart.convertFromPixel('grid', pointInPixel);
var category = myChart.getModel().get('xAxis')[0].data[pointInGrid[0]]
console.log(category);
});
参见示例:
var myChart = echarts.init(document.getElementById('main'));
var option = {
title: {
text: 'ECharts'
},
tooltip: {},
legend: {
data: ['Label']
},
xAxis: {
data: ["Category1", "Category2", "Category3", "Category4", "Category5", "Category6"]
},
yAxis: {},
tooltip: {
trigger: "axis",
confine: true,
enterable: true,
axisPointer: {
type: "shadow",
shadowStyle: {
color: "rgba(255,0,0, 0.5)"
}
},
backgroundColor: "rgba(255,255,255,1)",
textStyle: {
color: "#6D6D70"
},
extraCssText: `box-shadow: 3px 6px 14px #cccccc61;border-radius: 10px;`
},
series: [{
name: 'Series',
type: 'bar',
data: [5, 20, 36, 10, 10, 20],
showBackground: true,
}]
};
myChart.setOption(option);
myChart.getZr().on('click', params => {
var pointInPixel = [params.offsetX, params.offsetY];
var pointInGrid = myChart.convertFromPixel('grid', pointInPixel);
var category = myChart.getModel().get('xAxis')[0].data[pointInGrid[0]]
console.log(category);
});
<script src="https://cdn.jsdelivr.net/npm/echarts@4.9.0/dist/echarts.min.js"></script>
<div id="main" style="width: 600px;height:400px;"></div>
添加回答
举报