模拟点击触发 echarts 的 click 事件
手动触发 echarts 点击事件
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ECharts</title> <script src="https://cdn.staticfile.org/echarts/4.7.0/echarts.min.js"></script> <script src="https://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script> <style> .box { position: absolute; left: 0; top: 0; background: radial-gradient(ellipse at bottom, #1B2735 0%, #090A0F 100%); opacity: .5; } </style> </head> <body> <div id="app" style="width: 600px; height:400px;"></div> <div class='box' style="width: 600px; height:400px;"></div> </body> <script> const myChart = echarts.init(document.getElementById('app')) const option = { series: [{ type: 'pie', radius: [25, 95], center: ['50%', 140], roseType: 'area', clockWise: false, itemStyle: { normal: { label: { formatter: ['{b}', '占比{d}%'].join('\n'), textStyle: { color: '#000', fontSize: 16 } }, } }, data: [ { value: 5, name: '其他类' }, { value: 10, name: '就业保障类' }, { value: 15, name: '城市建设类' }, { value: 25, name: '民政救济类' }, { value: 20, name: '市场监管类' }, { value: 35, name: '市容城管类' }, { value: 30, name: '公共安全类' }, { value: 40, name: '公安消防类' } ] }] } myChart.setOption(option) myChart.on('click', function (e) { alert('触发点击事件') console.log(20211112141957, e) }) ////////////////////// // 模拟点击 - 核心代码 // ////////////////////// document.querySelector('.box').addEventListener('click', e => { const evmousedown = document.createEvent('HTMLEvents') evmousedown.initEvent('mousedown', false, true) const evmouseup = document.createEvent('HTMLEvents') evmouseup.initEvent('mouseup', false, true) const evmouseclick = document.createEvent('HTMLEvents') evmouseclick.initEvent('click', false, true) for(const key in event) { try { evmouseclick[key] = event[key] evmousedown[key] = event[key] evmouseup[key] = event[key] } catch (err) { /* event 对象中部分属性是只读,忽略即可 */ } } // 事件触发的容器,即不是 #app 也不是 canvas,而是中间这个 div const container = myChart._dom.firstElementChild container.dispatchEvent(evmousedown) container.dispatchEvent(evmouseup) container.dispatchEvent(evmouseclick) }) </script> </html>
事件触发的容器,即不是 #app 也不是 canvas,而是中间这个 div![](https://img2020.cnblogs.com/blog/922445/202111/922445-20211112152604634-802926847.png)