遇到一需求,一般都是点击图后获取其中一组数据就可以了,不需要详细到获取点击了当前X轴对应的其中的哪个,
今天的需求是 Echarts点击多组数据多个柱子中的一个柱子,获取当前点击的是第几组数据,并获取点击的是当前组别第几根柱子,以及对应横坐标
下面是解决方案
先上图


再上代码
option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
crossStyle: {
color: '#999'
}
}
},
toolbox: {
feature: {
dataView: { show: true, readOnly: false },
magicType: { show: true, type: ['line', 'bar'] },
restore: { show: true },
saveAsImage: { show: true }
}
},
legend: {
data: ['Evaporation', 'Precipitation', 'Temperature']
},
xAxis: [
{
type: 'category',
data: ['名字01', '名字02', '名字03', '名字04', '名字05', '名字06', '名字07'],
axisPointer: {
type: 'shadow'
}
}
],
yAxis: [
{
type: 'value',
name: 'Precipitation',
min: 0,
max: 250,
interval: 50,
axisLabel: {
formatter: '{value} ml'
}
}
],
series: [
{
name: 'Evaporation',
type: 'bar',
data: [
2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6
]
},
{
name: 'Precipitation',
type: 'bar',
data: [
2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6
]
},
{
name: 'Temperature',
type: 'bar',
data: [22.0, 23.2, 43.3, 44.5, 56.3, 130.2, 200.3]
}
]
};
myChart.getZr().off();
myChart.getZr().on('click', params => {
const actionObj = params.target
console.log('actionObj', actionObj)
const myKey = Object.keys(actionObj).sort().filter(_ => _.indexOf('ec_inner') !== -1)[0]
console.log('myKey', myKey)
const res = actionObj[myKey]
console.log(`当前点击了第${res.dataIndex}组数据中的第${res.seriesIndex}个柱子`)
var pointInPixel = [params.offsetX, params.offsetY];
if (myChart.containPixel('grid', pointInPixel)) {
var pointInGrid = myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel);
var xIndex = pointInGrid[0];
console.log('点击了横纵坐标', pointInPixel)
console.log('【点击了第几组数据,纵坐标】', pointInGrid)
var op = myChart.getOption();
console.log('数据信息', op)
var xValue = op.xAxis[0].data[xIndex];
console.log('x轴所对应的名字', xValue)
console.log('点击的这个柱子的名字', op.series[res.seriesIndex].name,'点击的这个柱子的值',op.series[res.seriesIndex].data[res.dataIndex])
}
});
最后希望路过的可以提供一下更好的方案哦~~~
学无止境,合作共赢!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决