echarts 折线图-tooltip提示框样式及定位处理

56 阅读1分钟

image.png

提示框 formatter、position

const  mockData = ref({
  "2025-03-21": [
    "12.1.1.1",
    ……
  ],
  "2025-03-22": [
    "12.1.1.1",
    "11.2.1.1",
    "12.3.1.1",
    "",
    ……
  ],
  ……
  x: [ "2025-03-21", "2025-03-22", "2025-03-23", "2025-03-24", ……],
  y: [18, 18, 5, 6, 9, 11, 8, 9]
});

const options = reactive({
  tooltip: {
    trigger: 'axis',
    triggerOn: 'click',
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    borderColor: '#aadeec',
    borderWidth: 1,
    textStyle: {
      color: '#303133',
      fontSize: 14
    },
    formatter: function(params) {
      const date = params[0].name;
      const ips = mockData.value[date] || [];
      let html = `<div class="tooltip-content" style="pointer-events: auto !important;">
        <div class="tooltip-title">${date}</div>
        <div class="tooltip-divider"></div>
        <div class="tooltip-ip-list">`;
      
      if (ips.length === 0) {
        html += '<div class="no-ip">暂无数据</div>';
      } else {
        ips.forEach(ip => {
          html += `<div class="ip-item">${ip || '未知IP'}</div>`;
        });
      }
      
      html += '</div></div>';
      return html;
    },
    position: function (pos, params, el, elRect, size) {
      const obj = {
        top: pos[1] - 10
      };
      // 根据鼠标位置决定提示框显示在左侧还是右侧
      if (pos[0] < size.viewSize[0] / 2) {
        obj.left = pos[0] + 10;
      } else {
        obj.right = size.viewSize[0] - pos[0] + 10;
      }
      return obj;
    },
    extraCssText: 'pointer-events: auto !important; z-index: 100;'
  },
  ……
});

点击示例:

image.png

echarts 官方配置文档

image.png

提示框样式添加

:deep(.tooltip-content) {
  padding: 8px;
  max-width: 300px;
  pointer-events: auto !important;
}

:deep(.tooltip-title) {
  font-weight: bold;
  color: #0399BF;
  margin-bottom: 8px;
  font-size: 14px;
}

:deep(.tooltip-divider) {
  height: 1px;
  background: #e4e7ed;
  margin: 8px 0;
}

:deep(.tooltip-ip-list) {
  max-height: 200px;
  overflow-y: auto;
  padding-right: 4px;
  pointer-events: auto !important;
  
  &::-webkit-scrollbar {
    width: 4px;
  }
  &::-webkit-scrollbar-thumb {
    background: #aadeec;
    border-radius: 2px;
  }
  &::-webkit-scrollbar-track {
    background: #f1fcff;
    border-radius: 2px;
  }
}

:deep(.ip-item) {
  padding: 6px 8px;
  background: #f1fcff;
  border-radius: 4px;
  margin-bottom: 4px;
  font-size: 13px;
  color: #303133;
  transition: all 0.3s;
  cursor: pointer;
  
  &:hover {
    background: #e6f7ff;
  }
  &:last-child {
    margin-bottom: 0;
  }
}

:deep(.no-ip) {
  text-align: center;
  color: #909399;
  padding: 12px 0;
  font-size: 13px;
}