做爲前端人員,難免會被產品虐出暴脾氣,甚至早已有小夥伴偷偷在鍵盤下藏了菜刀,你腦海中浮現着產品跪地求饒樣子,(此處省略無限字)…
咳~醒醒
設計往往天馬行空,這就苦了我們這些老實本分的前端同學,比如說,產品需求是這樣的
日常效果卻是這樣的
難度加倍,而薪資卻不加倍,一個悲傷的故事,
在殺死無數腦細胞後,終於完成
var data0 = [0, 0, 0, 0, 0, 0, 0]
var data = [60, 85, 110, 160, 90, 80, 190]
var xdata = ['06-02', '06-03', '06-04', '06-05', '06-06', '06-07', '06-08']
// 定義變量xIndex 表示X軸序號, Ymonth 表示柱狀圖的label值
var xIndex,Ymonth
option = {
// 關閉提示框, 替換爲柱狀圖的點擊事件
tooltip: {
trigger: "none"
},
title: {
text: "收益趨勢圖",
subtext: '用散點圖代替柱狀圖兩端點,並給柱狀圖添加點擊事件,簡約風格,很適合移動端',
textStyle: {
color: "#010001",
fontSize: 26
},
subtextStyle: {
color: "#5B5BFA",
fontSize: 14
},
left: 'center',
top: "15%"
},
grid: {
left: "10%",
top: "35%",
bottom: "15%",
right: "10%",
containLabel: true
},
xAxis: {
data: xdata,
type: 'category',
splitLine: {
show: false
},
axisLine: {
show: false
},
axisTick: {
show: false
},
axisLabel: {
color: '#383738',
fontSize: 14,
margin: 20
}
},
yAxis: {
type: 'value',
splitNumber: 4,
interval: 50,
splitLine: {
show: true,
lineStyle: {
color: '#D5D5D5',
type: 'dashed'
}
},
axisLine: {
show: false,
},
axisTick: {
show: false
},
axisLabel: {
color: '#383738',
fontSize: 14
}
},
series: [{
type: 'bar',
barWidth: 4,
data: data,
color: ['#F14845'],
label: {
show: true,
position: 'top',
// 標籤刻度值位置
offset: [0, -15],
fontSize: 16,
formatter: function(params) {
// 判斷收益是否大於0, 或者是否對應當前數據
if(params.value === 0 || params.value !== Ymonth) {
return ''
} else {
return params.value
}
}
}
},
{
type: 'scatter',
symbolSize: 8,
itemStyle: {
borderWidth: 2.5,
borderColor: '#F14845',
color: "#fff",
opacity: 1
},
silent: true,
data: data0
},
{
type: 'scatter',
symbolSize: 8,
itemStyle: {
borderWidth: 2.5,
borderColor: '#F14845',
color: "#fff",
opacity: 1
},
silent: true,
data: data
}
]
}
// 給每條數據的熱區增加點擊事件
myChart.getZr().on('click', function(params) {
var pointInPixel= [params.offsetX, params.offsetY]
if (myChart.containPixel('grid', pointInPixel)) {
var pointInGrid = myChart.convertFromPixel({seriesIndex: 0}, pointInPixel)
// X軸序號
xIndex = pointInGrid[0]
// 獲取當前圖表的option
var op = myChart.getOption()
// 獲得圖表中我們想要的數據
Ymonth = op.series[0].data[xIndex]
// console.log('點擊了第' + xIndex + '條數據')
myChart.setOption({
xAxis: [{
axisLabel: {
textStyle: {
color: function(value, index) {
return index === xIndex ? '#F14845' : '#383738'
}
}
}
}]
})
}
})
最終效果圖
最近有小夥伴問我,當使用了dataZoom捲動echart圖表後,橫座標的index錯位的情況,因爲我當前需求不涉及dataZoom,現在既然提到,那就來解決好了,其實很簡單
將紅色圈起部分改成
return value === xdata[xIndex] ? '#F14845' : '#383738'
分析原因, 前面求出的xIndex值是沒錯的,捲動情況下x軸index既然不管用,那就用value值去判斷