Detect Document Height Change

后端 未结 8 1083
独厮守ぢ
独厮守ぢ 2020-12-04 10:07

I\'m trying to detect when my document height changes. Once it does, I need to run a few functions to help organize my page layout.

I\'m not looking fo

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 10:49

    Update: 2020

    There is now a way to accomplish this using the new ResizeObserver. This allows you to listen to a whole list of elements for when their element changes size. The basic usage is fairly simple:

    const observer = new ResizeObserver(entries => {
      for (const entry of entries) {
        // each entry is an instance of ResizeObserverEntry
        console.log(entry.contentRect.height)
      }
    })
    observer.observe(document.querySelector('body'))
    

    The one downside is that currently there is only support for Chrome/Firefox, but you can find some solid polyfills out there. Here's a codepen example I wrote up:

    https://codepen.io/justin-schroeder/pen/poJjGJQ?editors=1111

提交回复
热议问题