JavaScript * DOM: 监听div的resize事件

我们平时在监听resize变化时,一般监听的都是window/body。

  • 可以绑定onresize的标签 body
  • 可以绑定onresize的对象 window
  • 只有一个起作用,后定义覆盖前定义的

但是有时我们希望监听div的resize变化该怎么办呢?尤其是现在css提供了resize属性。

解决方案如下:
  1. 通过添加object(text/html), http://www.backalleycoder.com
  2. https://github.com/sdecima
  3. https://caniuse.com
  4. 定时器 + getComputeStyle
  5. 基于resze和MutationOberver https://github.com/que-etc/re...
写了一个小示例,基于ResizeObserver API
<!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>
  <body>
    <div
      id="div"
      style="
        width: 300px;
        height: 300px;
        border: 1px solid red;
        resize: both;
        overflow: hidden;
      "
    ></div>
    <script>
      const resizeObserver = new ResizeObserver(onResize);
      resizeObserver.observe(document.querySelector('#div'));

      function onResize(e) {
        console.log(e);
      }
    </script>
  </body>
</html>

运行结果

参考地址:
https://segmentfault.com/q/1010000011959064
https://juejin.cn/post/7068542198047834126

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容