let data = [100,20,-40,50,-10] //真实数值 let data1 = [] data.map(item=>{ //把负值都变成整数,放在新的数组里,用来展示柱形高度 let newdata=0 if(item < 0){ newdata = -item }else{ newdata = item } data1.push(newdata) }) // 基于准备好的dom,初始化echarts实例 if(document.getElementById('balance')){ let myChart = echarts.init(document.getElementById('balance')); // 绘制图表 let option = { color: ["#E47373"], tooltip: { trigger: "axis", axisPointer: { type: "shadow" }, backgroundColor: 'rgba(51, 51, 51, 0.8)', borderWidth: 0, textStyle: { color: '#FFFFFF', fontSize: 12, }, formatter: function(params){ let res; res = '<div>' + '<div class="echarts-bar-tooltip" style="text-align: center">' + '<span style="width: 6px;height: 6px;border-radius: 50%;display:block;float:left;margin: 6px 4px 0 0;background: #E47373"></span>' + params[0].axisValue + '</div>' + '<div style="text-align: center">¥' + data[params[0].dataIndex] + '元</div>' + '</div>' return res //鼠标划过展示真实数值 } }, grid: { left: "0", top: '0', bottom: '0' }, xAxis: { type: 'category', data:["资金1", "资金2", "资金3", "资金4", "资金5"], show: false, position: 'bottom', offset: 0 }, yAxis: { type: 'value', show: false }, series: [{ data: data1, type: 'bar', itemStyle: { normal: { color: function (farams){ if(data[farams.dataIndex] > 0){ //根据真实数值正负显示不同柱形颜色 return '#E47373' }else{ return '#27CDA2' } } } } }] }; myChart.setOption(option) window.addEventListener("resize", function () { myChart.resize(); })
这是我第一次写,感谢小王同志的支持。