Detect Document Height Change

后端 未结 8 1100
独厮守ぢ
独厮守ぢ 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:47

    You can use an absolute positioned iframe with zero width inside the element you want to monitor for height changes, and listen to resize events on its contentWindow. For example:

    HTML

    
      Your content...
      
    
    

    CSS

    body {
      position: relative;
    }
    .height-change-listener {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      height: 100%;
      width: 0;
      border: 0;
      background-color: transparent;
    }
    

    JavaScript (using jQuery but could be adapted to pure JS)

    $('.height-change-listener').each(function() {
      $(this.contentWindow).resize(function() {
        // Do something more useful
        console.log('doc height is ' + $(document).height());
      });
    });
    

    If for whatever reason you have height:100% set on body you'll need find (or add) another container element to implement this on. If you want to add the iframe dynamically you'll probably need to use the