今天我们公司做前段设计师做了一个挺有意思的柱状图页面,我说这种的不好搞啊,时间又比较紧,他说领导就要这种的,在万般无奈下,我只能硬着头皮上了
一开始我是想着自己写,好控制,但是渐渐的我放弃了,这种要考虑好多兼容性问题,后来还死活选择了Echarts这个图表插件,看我效果
鼠标点击某一个柱子,就会变色,而且奇怪的是X轴显示的要设置css样式,抓狂了一阵后,终于琢磨出来了,看下代码
setBarOption:function(){
this.monthByYear=[
{month:'1月',count:10},{month:'2月',count:30},{month:'3月',count:10},{month:'4月',count:6},{month:'5月',count:22},{month:'6月',count:20},
{month:'7月',count:40},{month:'8月',count:10},{month:'9月',count:5},{month:'10月',count:1},{month:'11月',count:0},{month:'12月',count:11}
];
let xAxis=[];
let seriesData=[];
for(let i=0;i<this.monthByYear.length;i++){
xAxis.push(
{
value:this.monthByYear[i].month.length<3?' '+this.monthByYear[i].month+' ':this.monthByYear[i].month,
textStyle:{
borderColor:'rgba(203,211,213,1)',//X轴标签的边框色
backgroundColor:'rgba(255,255,255,1)',//X轴标签的背景色
borderWidth:'2px',//X轴标签的边框宽度
borderRadius:36,//X轴标签的圆角
padding:[10,3,10,3],//X轴标签的内边距
fontFamily:'PingFangSC',
fontWeight:400,
color:'rgba(57,84,91,1)',
fontSize:14
}
}
)
seriesData.push(
{
value:this.monthByYear[i].count,
itemStyle : {
normal : {
color: 'rgba(66,195,252,1)'//Y轴数据的背景色
}
}
}
);
}
this.barOption = {
color: ['rgba(66,195,252,1)'],
tooltip : {
trigger: 'axis',
showContent:false,
axisPointer : { // 坐标轴指示器,坐标轴触发有效
type : 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
grid: {//柱状图上下左右的边距
top:'12%',
left: '3%',
right: '4%',
bottom: '18%',
containLabel: true
},
xAxis : [
{
type : 'category',
triggerEvent:true,//X轴标签可点击
axisLine:{
lineStyle:{
color:'#F7F8F8'
}
},
axisLabel:{
color:'rgba(57,84,91,1)'
},
data : xAxis,
axisTick: {
show: false
}
}
],
yAxis : [
{
type : 'value',
show:false
}
],
series : [
{
name:'直接访问',
type:'bar',
barWidth: '30%',
label: {//Y轴数据值显示的位置和样式
show: true,
position: 'top',
textStyle: {
color: 'rgba(57,84,91,1)',
fontSize:14
}
},
data:seriesData
}
]
};
return this.barOption;
}
然后再添加点击事件的样式调整
that.barChart.on('click', function (params) {
let dataName='1月';
if(params.componentType==="xAxis"){
dataName=params.value.trim();
}else if(params.componentType==="series"){
dataName=params.name.trim();
}
for(let i=0;i<that.monthByYear.length;i++){
if(that.monthByYear[i].month===dataName){
that.barOption.series[0].data[i].itemStyle.normal.color='rgba(24,144,255,1)';
that.barOption.xAxis[0].data[i].textStyle.backgroundColor='rgba(24,144,255,1)';
that.barOption.xAxis[0].data[i].textStyle.color='rgba(255,255,255,1)';
}else{
that.barOption.series[0].data[i].itemStyle.normal.color='rgba(66,195,252,1)';
that.barOption.xAxis[0].data[i].textStyle.backgroundColor='rgba(255,255,255,1)';
that.barOption.xAxis[0].data[i].textStyle.color='rgba(57,84,91,1)';
}
}
that.barChart.setOption(that.barOption);
});