鼠标移入x轴标题弹出框

103 阅读1分钟

可以使用之前的3d柱形图为例

在xAxis中新增triggerEvent属性

 xAxis: {
    triggerEvent:true,
},

在xAxis的axisLabel中新增formatter来控制换行及省略号显示

formatter: function(value){
    let ret = "";
    const maxLength = 6;
    const maxRow = 2;
    const valLength = value.length;
    const rowN = Math.ceil(valLength / maxLength);
    if (rowN > 1){
      let i = 0
      let temp = "";
      for (; i < maxRow - 1; i++){
        const start = i * maxLength;
        const end = start + maxLength;
        temp = value.substring(start, end) + "\n";
        ret += temp
      }
      const start = i * maxLength;
      const end = start + maxLength;
      if (rowN > maxRow){
        temp = value.substring(start, end-1) + "...";
      } else {
        temp = value.substring(start, end);
      }
      ret += temp
      return ret
    } else {
      return value
    }
},

x轴文字靠左修改formatter中的return,并新增rich属性(毕竟大屏是响应式的,不能通过定位微调)

formatter: function(value){
    if (rowN > 1){
      ....
     return "{a|" + ret + "}";
    } else {
      return value
    }
},
 rich:{
    a:{
      align: "left",
    }
  },

在页面上新增需要弹出的框,这里是写在vue文件中(此处用px是因为echarts重新渲染后适配了当前大屏像素,但有误差,想要完全响应式可以参考Vue使用v-bind动态定义css)

<template>
    <div ref="ChartRef" class="plain-box"></div>
    <div class="extension"
    :style="{
        top:`${top}px`,
        left:`${left}px`,
        display:display,
    }"
    >
        {{ text }}
    </div>
</template>
<script setup>
import {ref} from "vue";
const text = ref("");
const top = ref(0);
const left = ref(0);
const display = ref("none");
.... (假设getInstance()可以获取echarts势力)
getInstance()?.on("mouseover", (param) => {
    if (param.componentType === "xAxis"){
        text.value = param.value;
        top.value = param.event.offsetY + 15;
        left.value = param.event.offsetX - 10;
        display.value = "block"
    }
});
getInstance()?.on("mouseout", (param) => {
    if (param.componentType === "xAxis"){
         display.value = "none"
    }
});
</script>
<style lang="less">
.extension {
    display: none;
    position: relative;
    top: 0;
    left: 0;
    padding: 2px 5px;
    border-radius: 4px;
    background-color: #ffffff80;
    color: #333;
    white-space: nowrap;
} 
</style>