项目中遇到一个功能,使用echarts时 X轴的文本过长,需要溢出文字用省略号显示,然后鼠标悬浮提示全部文本最终功能效果如下,没有溢出省略号的,鼠标悬浮没提示,溢出的鼠标悬浮提示,如下gif展示;
代码如下
<div class="myEcharts" id="barMyEcharts" style="width: 680px;height: 300px;background: black">
<div id="basicBar" ref="Bar" style="width: 580px;height: 300px"></div>
<div class="extension" id="extension"></div>
</div>
HTML
<script>
import * as echarts from "echarts";
export default {
name: "login",
data() {
return {
}
},
mounted() {
this.getBarData()
},
methods: {
getBarData() {
var chartDom = document.getElementById('basicBar');
var myChart = echarts.init(chartDom);
var success = [], fail = [],xAxisData=[]
const barDataList = [
{name:'这个是短的',success:'50',fail:'18'},
{name:'这个是长的标题哦,会省略和悬浮',success:'40',fail:'48'},
]
for (let i = 0; i < barDataList.length; i++) {
success.push(barDataList[i].success)
fail.push(barDataList[i].fail)
xAxisData.push(barDataList[i].name)
}
myChart.setOption({
title: {
text: '柱形图',
left: 'center',
top: 0,
textStyle: {
color: '#fff'
}
},
legend: {
data: ['成功', '失败'],
left: '20%',
bottom: 0,
textStyle: {
color: '#fff'
}
},
tooltip: {},
xAxis: {
data: xAxisData,
triggerEvent:true,//这个一定要加上;
type: 'category',
splitLine: {show: false},
splitArea: {show: false},
axisLabel: {
interval: 0, //横轴信息全部显示
rotate: 30, // 倾斜角度
formatter: function (value) {
return value.length > 8 ? value.substring(0, 8) + '...' : value;
}
}
},
yAxis: {
splitLine: {show: false},
splitArea: {show: false},
},
grid: {
bottom: 100
},
series: [
{
name: '成功',
type: 'bar',
stack: 'one',
label: {
show: true,
color: '#fff'
},
itemStyle: {
},
data: success
},
{
name: '失败',
type: 'bar',
stack: 'one',
label: {
show: true,
color: '#fff'
},
itemStyle: {
},
data: fail
}
]
});
this.setHoverFn()
},
// 获取鼠标位置坐标方法
mouseMove(e) {
e = e || window.events;
return this.mousePosition(e.event);
},
mousePosition(ev) {
if (ev.pageX || ev.pageY) {
return {x: ev.pageX, y: ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.scrollTop
};
},
setHoverFn(){
//设置超出省略,鼠标悬浮显示
var that = this;
var line = echarts.init(this.$refs.Bar);
line.on('mouseover',function (params){
let extension = document.getElementById('extension');
if(params.componentType == "xAxis" && params.value.length > 8){
let mousePos = that.mouseMove(params.event);
let x = mousePos.x;
let y = mousePos.y - 40;
extension.innerHTML = params.value;
extension.style.cssText = "top:" + y + "px;left:" + x + "px;display:inline;position:fixed;";
} else {
let extension = document.getElementById("extension");
extension.style.cssText = "display:none"
}
});
document.getElementById('barMyEcharts').addEventListener('mouseleave',function (params){
let extension = document.getElementById("extension");
extension.style.cssText = "display:none"
})
}
}
}
</script>
<style scoped>
.extension{
display: none;
background: white;
border: 2px;
padding: 10px;
border-radius: 5px;
}
</style>