1. 确认echarts默认效果
echarts默认点击图例有如下效果:
- 当前图例显示,点击后隐藏该图例;
- 当前图例隐藏,点击后显示该图例。
2. 确认需要处理的事件
经过在官网查看事件后发现最合适的是legendselectchanged事件,该事件在切换图例选中状态时触发。
具体用法为:
javascript
myChart.on('legendselectchanged', params => {})
3. 将目标简单化
由于echarts本身自带是否显示影藏,那我们只需要在这个基础上优化以下两点即可:
- 当所有图例都不显示的时候显示全部图例;
- 当除了当前点击图例,其他图例都显示的时候(也就是全部显示的情况下点击了当前图例),只显示当前图例。
4. 代码实现
javascript
myChart.on('legendselectchanged', params => {
const curLegend = params.name;
const allLegend = Object.keys(params.selected);
const selectedArr = Object.keys(params.selected).filter(el => params.selected[el])
const clearFlag = selectedArr.length === 0
const onlyCur = selectedArr.length + 1 === allLegend.length && !selectedArr.includes(curLegend);
if (clearFlag) {
allLegend.forEach(key => {
myChart.dispatchAction({
type: 'legendSelect',
name: key,
})
})
}
if (onlyCur) {
allLegend.forEach(key => {
myChart.dispatchAction({
type: key === curLegend ? 'legendSelect' : 'legendUnSelect',
name: key,
})
})
}
})
4. 完整代码
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ECharts</title>
<!-- 引入刚刚下载的 ECharts 文件 -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/echarts.min.js"></script>
</head>
<body>
<!-- 为 ECharts 准备一个定义了宽高的 DOM -->
<div id="main" style="height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 指定图表的配置项和数据
var option = option = {
title: {
text: 'Stacked Line'
},
tooltip: {
trigger: 'axis'
},
legend: {
data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
name: 'Email',
type: 'line',
stack: 'Total',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: 'Union Ads',
type: 'line',
stack: 'Total',
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: 'Video Ads',
type: 'line',
stack: 'Total',
data: [150, 232, 201, 154, 190, 330, 410]
},
{
name: 'Direct',
type: 'line',
stack: 'Total',
data: [320, 332, 301, 334, 390, 330, 320]
},
{
name: 'Search Engine',
type: 'line',
stack: 'Total',
data: [820, 932, 901, 934, 1290, 1330, 1320]
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
myChart.on('legendselectchanged', params => {
const curLegend = params.name;
const allLegend = Object.keys(params.selected);
const selectedArr = Object.keys(params.selected).filter(el => params.selected[el])
const clearFlag = selectedArr.length === 0
const onlyCur = selectedArr.length + 1 === allLegend.length && !selectedArr.includes(curLegend);
if (clearFlag) {
allLegend.forEach(key => {
myChart.dispatchAction({
type: 'legendSelect',
name: key,
})
})
}
if (onlyCur) {
allLegend.forEach(key => {
myChart.dispatchAction({
type: key === curLegend ? 'legendSelect' : 'legendUnSelect',
name: key,
})
})
}
});
</script>
</body>
</html>