1. 程式人生 > 其它 >JavaScript監聽DOM的resize事件

JavaScript監聽DOM的resize事件

1.使用第三方庫

  安裝:npm install observabledomevent -S

     或者

     yarn addobservabledomevent

  使用:

    1.直接引用檔案

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport"
content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <style> #contanier { width: 500px; height: 300px; display: flex; align-items: center; border: 1px solid red; }
.left { width: 100px; border-right: 1px solid blue; height: 100%; } .right { width: calc(100% - 100px); height: 100%; } .echarts { width: 100%; height: 100%; } </style> <
body> <div id="contanier"> <div class="left">left</div> <div class="right"> <div class="echarts"></div> </div> </div> <button class="btnLeft">hide left</button> <button class="btnRight">show left</button> </body> <script src="./observabledomevent.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.1.2/echarts.js"></script> <script> const contanier = document.getElementById('contanier'); const _echarts = document.querySelector('.echarts'); const leftContanier = document.querySelector('.left'); const rightContanier = document.querySelector('.right'); const btnLeft = document.querySelector('.btnLeft'); const btnRight = document.querySelector('.btnRight'); const observableDom = new observabledomevent.ObservableDomEvent(_echarts); const option = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { data: [820, 932, 901, 934, 1290, 1330, 1320], type: 'line', smooth: true } ] }; const echartsInstance = echarts.init(_echarts); echartsInstance.setOption(option, true); observableDom.$on('resize', () => { echartsInstance.resize(); }); btnLeft.onclick = function () { leftContanier.style.display = 'none'; rightContanier.style.width = '100%'; }; btnRight.onclick = function () { leftContanier.style.display = 'block'; rightContanier.style.width = 'calc(100% - 100px)'; }; </script> </html>

  2.更多使用請檢視:

    observabledomevent - npm (npmjs.com)