• echarts 实现tooltip自动轮播显示,鼠标悬浮时暂停


    在ECharts中,可以通过设置 tooltip.trigger="axis" ,来显示数据轴上的提示框
    实现tooltip的自动轮播显示,结合使用 setInterval()dispatchAction()方法。
    获取chart DOM 实例,监听鼠标事件,悬浮时清空定时器,鼠标离开开启定时器,继续轮播。

    “vue”: “^3.2.47”,
    “echarts”: “^5.4.1”,

    • 效果
      在这里插入图片描述

    实现步骤

    • 设置 tooltip
    tooltip: {
    	trigger: 'axis',
    },
    
    • 1
    • 2
    • 3
    • 获取当前图表数据项length,并定义 currentIndex 用于记录当前显示的数据项索引。
    const xData = Array.from({ length: 31 }, (_, i) => i + 1);
    let currentIndex = -1; // 初始值为-1,表示未开始轮播
    
    • 1
    • 2
    • 使用 setInterval()定时触发 dispatchAction(),切换tooltip的显示内容。
    let timer = <TimerType>undefined;
    let currentIndex = -1;
    
    // 切换tooltip
    function switchTooltip(myChart) {
    	// 取消之前高亮的图形
    	myChart.dispatchAction({
    		type: 'downplay',
    		seriesIndex: 1,
    		dataIndex: currentIndex,
    	});
    
    	currentIndex = (currentIndex + 1) % 31;
    	// 高亮当前图形
    	myChart.dispatchAction({
    		type: 'highlight',
    		seriesIndex: 1,
    		dataIndex: currentIndex,
    	});
    	// 显示tooltip
    	myChart.dispatchAction({
    		type: 'showTip',
    		seriesIndex: 1,
    		dataIndex: currentIndex,
    	});
    }
    
    function startTooltipLoop(myChart) {
    	timer = setInterval(() => switchTooltip(myChart), 3000);
    }
    
    function closeSwitchTooltip() {
    	timer = undefined;
    	clearInterval(timer);
    }
    
    // 开启轮播
    startTooltipLoop(myChart);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 监听鼠标事件,悬浮时停止轮播,离开继续轮播
    const myChart = echarts.init(unref(lineChartIntanse)!);
    
    // 鼠标悬浮,停止轮播
    myChart.on('mousemove', function () {
    	closeSwitchTooltip();
    });
    
    // 鼠标离开,继续轮播
    myChart.on('mousedown', function () {
    	startTooltipLoop(myChart);
    });
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 完整代码
    • lineChart.ts
    import * as echarts from 'echarts';
    import { Ref } from 'vue';
    import type { SalesTrendComparison, TimerType } from '../types';
    import { getSize } from '../utils';
    
    type EChartsOption = echarts.EChartsOption;
    
    export function useLineChart(lineChartIntanse: Ref<Nullable<HTMLElement>>, data: SalesTrendComparison[]) {
    	let timer = <TimerType>undefined;
    	let currentIndex = -1;
    
    	watch(
    		() => data,
    		async (data: Recordable) => {
    			closeSwitchTooltip();
    			await nextTick();
    			const getLineChartInstance = unref(lineChartIntanse) ? echarts.getInstanceByDom(unref(lineChartIntanse)!) : null;
    			getLineChartInstance ? getLineChartInstance.setOption({ series: getSeries(data) }) : initLineChart();
    		},
    		{ deep: true, immediate: true }
    	);
    
    	function initLineChart() {
    		const myChart = echarts.init(unref(lineChartIntanse)!);
    
    		const option = getOption();
    
    		startTooltipLoop(myChart);
    
    		myChart.on('mousemove', function () {
    			closeSwitchTooltip();
    		});
    
    		myChart.on('mousedown', function () {
    			startTooltipLoop(myChart);
    		});
    
    		myChart.setOption(option);
    	}
    
    	function getOption() {
    		const color = '#748497';
    		const xData = Array.from({ length: 31 }, (_, i) => i + 1);
    		const option: EChartsOption = {
    			tooltip: {
    				trigger: 'axis',
    				backgroundColor: '#364057',
    				borderColor: 'rgba(255,255,255,0.2)',
    				textStyle: {
    					color: '#FFFFFF',
    					lineHeight: getSize(12),
    					fontSize: getSize(14),
    					fontFamily: 'PingFangSC-Regular, PingFang SC',
    				},
    				axisPointer: {
    					type: 'line',
    				},
    				formatter: (params) => {
    					let result = '';
    					params.forEach((item, i) => {
    						const { seriesName, data, axisValue } = item;
    						const color = seriesName === '上月' ? '#FB497C' : '#5BE4F7';
    						if (i === 0) {
    							result += `${axisValue}日销售额
    `
    ; } result += markDot(color) + `${seriesName} ${data?.[1]}
    `
    ; }); return result; }, }, legend: { textStyle: { color: '#fff', fontSize: getSize(14), fontWeight: 500, lineHeight: getSize(12), fontFamily: 'PingFangSC-Medium, PingFang SC', }, itemHeight: getSize(8), }, grid: { top: '10%', left: '0', right: '4%', bottom: '7%', containLabel: true, }, xAxis: { type: 'category', boundaryGap: false, data: xData, axisLabel: { interval: 0, margin: getSize(13), color, fontSize: getSize(14), lineHeight: getSize(18), fontWeight: 600, fontFamily: 'PingFangSC-Regular, PingFang SC', }, axisTick: { show: false }, axisLine: { lineStyle: { color: '#0C3760', type: 'dashed', width: getSize(1) }, }, }, yAxis: { type: 'value', splitLine: { lineStyle: { color: '#0C3760', type: 'dashed', width: getSize(1) }, }, axisLabel: { color, fontFamily: 'PingFangSC-Medium, PingFang SC', fontWeight: 500, fontSize: getSize(14), lineHeight: getSize(20), margin: getSize(12), }, }, series: getSeries(data), }; return option; } // 生成大小一样样色不同的圆点 function markDot(color) { let domHtml = '+ 'display: inline-block;' + 'margin-right: 8px;' + 'margin-bottom: 2px;' + 'border-radius: 6px;' + 'width: 0.4167vw;' + 'height: 0.7407vh;' + `background-color: ${color}` + '">'; return domHtml; } function getSeries(data): EChartsOption['series'] { const common = { type: 'line', stack: 'Total', animation: false, symbol: 'circle', symbolSize: getSize(8), }; return data.map((item) => { return { name: item.name, data: item.data, ...common, emphasis: { itemStyle: { color: item.color, borderWidth: 0, }, }, itemStyle: { color: '#03122F', borderWidth: getSize(2), borderColor: item.color, }, lineStyle: { color: item.color, width: getSize(2), }, z: item.name === '本月' ? 6 : 1, }; }) as EChartsOption['series']; } // 切换tooltip function switchTooltip(myChart) { // 取消之前高亮的图形 myChart.dispatchAction({ type: 'downplay', seriesIndex: 1, dataIndex: currentIndex, }); currentIndex = (currentIndex + 1) % 31; // 高亮当前图形 myChart.dispatchAction({ type: 'highlight', seriesIndex: 1, dataIndex: currentIndex, }); // 显示tooltip myChart.dispatchAction({ type: 'showTip', seriesIndex: 1, dataIndex: currentIndex, }); } function startTooltipLoop(myChart, delay = 3000) { timer = setInterval(() => switchTooltip(myChart), delay); } function closeSwitchTooltip() { timer = undefined; clearInterval(timer); } const getSize = (size: number) => (document.body.clientWidth / 1920) * size; // 自适应 const onLineChartResize = () => { if (unref(lineChartIntanse)) { const chartInstance = echarts.getInstanceByDom(unref(lineChartIntanse)!); const option = getOption(); chartInstance?.setOption(option); chartInstance?.resize(); } }; return { onLineChartResize, switchTooltip, closeSwitchTooltip }; }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 引用
    	
    const saleRef = ref>(null); const { onLineChartResize, closeSwitchTooltip } = useLineChart(saleRef, data); window.addEventListener('resize', () => resizeChart()); onBeforeUnmount(() => { closeSwitchTooltip(); window.removeEventListener('resize', () => resizeChart()); });
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  • 相关阅读:
    VSCODE解决git合并过程中的冲突问题;error: failed to push some refs to
    【Java】面向对象程序设计 基础语法笔记
    IDEA 调试远程服务
    基于java+springboot+mybatis+vue+elementui的眼镜商城系统
    软件设计模式系列之二——抽象工厂模式
    项目中常用工具包
    MySQL体系结构和四层架构介绍
    【DIY飞控板PX4移植】BARO模块BMP388气压计的PCB硬件设计和PX4驱动配置
    js红宝书学习笔记(一)引用类型
    4.2 搭建LVS-DR模式
  • 原文地址:https://blog.csdn.net/weixin_47085255/article/details/134079361