如何在echarts条形图中使条形周围的空间可点击?

仅当恰好在栏内单击时才会触发“单击”事件。如果我们有一个宽度或高度较小的条形,这并不方便。当我将鼠标悬停在栏上时,栏周围的一些空间会以完整的图表高度突出显示,并显示工具提示。我想让突出显示的区域可点击,并且条形数据应该在事件中可用。我已经阅读了文档并尝试了 Chart.on('click', 'xAxis.category', function () {...}); 但该功能没有被触发。

在此演示中,仅当我在栏内单击时才会触发警报。如何使周围区域可点击?


繁花如伊
浏览 147回答 1
1回答

心有法竹

确实,点击栏外时无法接收到常见事件,但 Echarts 是成熟的框架,几乎任何事件都可以通过低级对象接收zRender。您需要访问zRenderwithgetZr()并将单击的像素的坐标转换为图表坐标。之后,您将拥有系列数据点的索引,通过它来获取类别将很容易。myChart.getZr().on('click', params => {&nbsp; var pointInPixel = [params.offsetX, params.offsetY];&nbsp; var pointInGrid = myChart.convertFromPixel('grid', pointInPixel);&nbsp; var category = myChart.getModel().get('xAxis')[0].data[pointInGrid[0]]&nbsp; console.log(category);});参见示例:var myChart = echarts.init(document.getElementById('main'));var option = {&nbsp; title: {&nbsp; &nbsp; text: 'ECharts'&nbsp; },&nbsp; tooltip: {},&nbsp; legend: {&nbsp; &nbsp; data: ['Label']&nbsp; },&nbsp; xAxis: {&nbsp; &nbsp; data: ["Category1", "Category2", "Category3", "Category4", "Category5", "Category6"]&nbsp; },&nbsp; yAxis: {},&nbsp; tooltip: {&nbsp; &nbsp; trigger: "axis",&nbsp; &nbsp; confine: true,&nbsp; &nbsp; enterable: true,&nbsp; &nbsp; axisPointer: {&nbsp; &nbsp; &nbsp; type: "shadow",&nbsp; &nbsp; &nbsp; shadowStyle: {&nbsp; &nbsp; &nbsp; &nbsp; color: "rgba(255,0,0, 0.5)"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; &nbsp; backgroundColor: "rgba(255,255,255,1)",&nbsp; &nbsp; textStyle: {&nbsp; &nbsp; &nbsp; color: "#6D6D70"&nbsp; &nbsp; },&nbsp; &nbsp; extraCssText: `box-shadow:&nbsp; 3px 6px 14px #cccccc61;border-radius: 10px;`&nbsp; },&nbsp; series: [{&nbsp; &nbsp; name: 'Series',&nbsp; &nbsp; type: 'bar',&nbsp; &nbsp; data: [5, 20, 36, 10, 10, 20],&nbsp; &nbsp; showBackground: true,&nbsp; }]};myChart.setOption(option);myChart.getZr().on('click', params => {&nbsp; var pointInPixel = [params.offsetX, params.offsetY];&nbsp; var pointInGrid = myChart.convertFromPixel('grid', pointInPixel);&nbsp; var category = myChart.getModel().get('xAxis')[0].data[pointInGrid[0]]&nbsp; 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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript