tooltip: {
formatter: function (params) {
//公式计算显示次数×权重 let result = params[0].name + "<br>"; params.forEach(function (item, i) { const seriesIndex = params[i].seriesIndex; const score = data[seriesIndex].score; if (parseInt(params[i].data) == 0) { result += params[i].marker + params[i].seriesName + ": " + params[i].data + "<br>"; } else { result += params[i].marker + params[i].seriesName + ": " + params[i].data + " ( " + parseInt(params[i].data / score) + "次" + " × " + score + " ) " + "<br>"; } }) return result; } },
七、 grid.containLabel
Y轴文字过长显示不全是使用
el: http://echarts.baidu.com/option.html#grid.containLabel
containLabel 为
true
的时候:这常用于『防止标签溢出』的场景,标签溢出指的是,标签长度动态变化时,可能会溢出容器或者覆盖其他组件。
grid: { left: 20 right: 20, bottom: '0', top: '0', containLabel: true },
***还有一种情况,初始化时显示的是文字长度,但是删除最长的文字那行,页面重新渲染后,Y轴的长度发生改变,文字还是显示不全***
1、找出最长的文字,根据设置的字体计算出文字长度
//尝试计算Y轴删除按钮的落点 let yAxisTextMaxoffsetX = 0; try { let yAxisTextMaxLength = 0; let yAxisTextMaxContent = ""; yAxis.forEach(function (item) { let len = 0; for (var i = 0; i < item.length; i++) { if (item.charCodeAt(i) > 255) { //汉字两个字符 len += 2; } else { len++; } } if (len > yAxisTextMaxLength) { yAxisTextMaxContent = item; } yAxisTextMaxLength = Math.max(len, yAxisTextMaxLength); }) yAxisTextMaxoffsetX = yAxisTextMaxLength * 6 //12px/2 console.log("最长的内容为:" + yAxisTextMaxContent + ",字符长度为:" + yAxisTextMaxLength + ",计算出的长度为:" + yAxisTextMaxoffsetX); } catch (error) { console.log(error); }
2、设置grid.left为最长文字长度
grid: { left: yAxisTextMaxoffsetX == 0 ? 20 : yAxisTextMaxoffsetX + 8,//yAxis.axisLabel.margin 默认为8 right: 20, bottom: '0', top: '0', containLabel: yAxisTextMaxoffsetX == 0 ? true : false, },
八、 yAxis.triggerEvent 与 yAxis.formatter yAxis.rich
Y轴增加图标,实现删除功能
el:
1、增加图标:使用formatter编辑返回值,搭配rich的backgroundColor增加删除图标。
http://echarts.baidu.com/option.html#yAxis.axisLabel.rich
yAxis: { type: 'category', axisLabel: { interval: 0, formatter: function (value, index) { return value + '{space|}' + '{del|}'; }, // rich 里是文本片段的样式设置: rich: { del: { width: 20, height: 20, align: 'center', backgroundColor: { image: '/static/hide.svg', }, }, space: { width: 3 } } }, data: yAxis, triggerEvent: true,//是否触发事件,param.componentType == "yAxis" },
2、删除功能:由于param返回的值少,只能根据鼠标落点,计算是否点击了图标。根据获取的value找出index,将数据删除
myChart.on('click', function (param) { if (param && param.componentType == "yAxis") { console.log("单击了" + param.value + "的Y轴标签" + ",位置在" + param.event.offsetX); if (yAxisTextMaxoffsetX != 0 && param.event.offsetX < yAxisTextMaxoffsetX) {// yAxisTextMaxoffsetX值的计算在上边第七里 return false; } let activeIndex = 0; yAxis.forEach(function (item, index) { if (item === param.value) { activeIndex = index; return; } }); yAxis.splice(activeIndex, 1); data.forEach(function (item) { item.data.splice(activeIndex, 1); }); //TO 重绘echarts } else { console.log("单击了" + param.name + "柱状图"); if (typeof callback === "function") { callback(); } } });