Skip to content

JS 监听 DOM 高度变化

Published: at 10:58 AMSuggest Changes

需要监听 dom 的高度变化,有时候图片未加载完就取 dom 的高度,这样会导致高度不正确,所以需要监听 dom 的高度变化

emmmm,下面的这段代码不是我写的,是 ai 自动补全的

var dom = document.getElementById('dom');
var height = dom.offsetHeight;
dom.addEventListener('DOMNodeInserted', function () {
  var newHeight = dom.offsetHeight;
  if (newHeight !== height) {
    console.log('dom 高度变化了');
    height = newHeight;
  }
});

这个是我目前用的

// create an Observer instance
const resizeObserver = new ResizeObserver((entries) =>
  console.log('Body height changed:', entries[0].target.clientHeight)
);

// start observing a DOM node
resizeObserver.observe(document.body);

// click anywhere to rnadomize height
window.addEventListener(
  'click',
  () =>
    (document.body.style.height = Math.floor(Math.random() * 5000 + 1) + 'px')
);

还有个 ResizeObserver 方法,不过是实验性功能

https://developer.mozilla.org/zh-CN/docs/Web/API/ResizeObserver

这个是监听窗口大小变化的

//listen for window resize event
window.addEventListener('resize', function(event){
    var newWidth = window.innerWidth;
    var newHeight = window.innerHeight;
});

另外一种方法 MutationObserver

  const mutationObserver = new MutationObserver(data => {
    console.log('MutationObserver');

    const clientHeight = detailDomTest.clientHeight;
    const scrollHeight = detailDomTest.scrollHeight;
    console.log('clientHeight', clientHeight);
    console.log('scrollHeight', scrollHeight);
    callHandler(
      'getWebviewSize',
      {
        clientHeight: scrollHeight
      },
      () => {
        return void 0;
      }
    );
  });


  mutationObserver.observe(detailDomTest, {
    attributes: true,
    childList: true // 子节点的变动(新增、删除或者更改)
  });

参考文章


Previous Post
JS OpenCV 入门教程
Next Post
解决 TypeScript 项目中 ESLint 关于 AMap 的报错问题