手動觸發 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