javascript - 单击echart条形图时如何突出显示条形?
问题描述
我使用 echarts 库创建了一个条形图。如何在用户单击条形图时突出显示条形图,或者在单击条形图时应用条形边框?
有没有办法在栏触发点击事件时突出显示栏?
解决方案
是的,有一种方法可以在单击时突出显示条。
当点击事件被触发时,您可以从参数中获取被点击的确切数据(单条),然后您只需要改变这些数据的颜色(例如,降低alpha)就可以达到'highlight'的目的。
并且不要同时忘记其他数据(未点击)的恢复颜色。
检查这个演示
let echartsObj = echarts.init(document.querySelector('#canvas'));
option = {
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [{
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
}],
yAxis: [{
type: 'value'
}],
series: [{
name: '直接访问',
type: 'bar',
barWidth: '60%',
data: [{
value: 10,
itemStyle: {
color: 'hsl(200,60%,45%)'
}
}, {
value: 52,
itemStyle: {
color: 'hsl(200,60%,45%)'
}
}, {
value: 200,
itemStyle: {
color: 'hsl(60,60%,45%)'
}
}, {
value: 334,
itemStyle: {
color: 'hsl(150,60%,45%)'
}
}, {
value: 390,
itemStyle: {
color: 'hsl(220,60%,45%)'
}
}, {
value: 330,
itemStyle: {
color: 'hsl(200,60%,45%)'
}
}, {
value: 220,
itemStyle: {
color: 'hsl(150,60%,45%)'
}
}]
}]
};
echartsObj.setOption(option)
echartsObj.on('click', function(params) {
console.log(params)
option.series[0].data.forEach((data, index) => {
if (index === params.dataIndex) {
if (!data.isChecked) {
data.itemStyle.color = getHighLightColor(data.itemStyle.color);
data.isChecked = true;
}
} else {
if (data.isChecked) {
data.itemStyle.color = getOrigColor(data.itemStyle.color);
data.isChecked = false;
}
}
})
echartsObj.setOption(option)
});
function getHighLightColor(color) {
return color.replace(/(\d+)%\)/, (...args) => {
return 20 + Number(args[1]) + '%)'
});
}
function getOrigColor(highlightColor) {
return highlightColor.replace(/(\d+)%\)/, (...args) => {
return Number(args[1]) - 20 + '%)'
});
}
<html>
<header>
<script src="https://cdn.bootcss.com/echarts/4.1.0.rc2/echarts-en.min.js"></script>
</header>
<body>
<div id="canvas" style="width: 100%; height: 200px">
</div>
</body>
</html>
推荐阅读
- mongodb - MongoDB v3.4.5 错误?
- r - Color in R plot
- php - 比较数组值并根据自定义值查找数组中的下一个值 (PHP)
- google-cloud-platform - 从本地计算机连接 GCP VPN 时遇到问题
- javascript - 从函数构造函数访问方法
- java - 带有客户端证书的 TLS 握手失败
- iframe - 允许相机访问 Safari iframe
- linux - 在保留列的同时在子字符串后添加空格
- javascript - JS 对象解构以访问属性以用于评估目的,而无需实例化变量
- mysql - Playframework 2.5 [Java]:我无法将一列数据插入我的数据库