make iframe height dynamic based on content inside- JQUERY/Javascript

前端 未结 20 2000
情书的邮戳
情书的邮戳 2020-11-22 07:42

I am loading an aspx web page in an iframe. The content in the Iframe can be of more height than the iframe\'s height. The iframe should not have scroll bars.

I have

相关标签:
20条回答
  • 2020-11-22 08:16

    This one is useful when you require a solution with no jquery. In that case you should try adding a container and set a padding to it in percentages

    HTML example code:

    <div class="iframecontainer">
        <iframe scrolling="no" src="..." class="iframeclass"width="999px" height="618px"></iframe>
    </div>
    

    CSS example code:

    .iframeclass{
        position: absolute;
        top: 0;
        width: 100%;
    }
    
    .iframecontainer{
        position: relative;
        width: 100%;
        height: auto;
        padding-top: 61%;
    }
    
    0 讨论(0)
  • 2020-11-22 08:17

    I found that the accepted answer didn't suffice, since X-FRAME-OPTIONS: Allow-From isn't supported in safari or chrome. Went with a different approach instead, found in a presentation given by Ben Vinegar from Disqus. The idea is to add an event listener to the parent window, and then inside the iframe, use window.postMessage to send an event to the parent telling it to do something (resize the iframe).

    So in the parent document, add an event listener:

    window.addEventListener('message', function(e) {
      var $iframe = jQuery("#myIframe");
      var eventName = e.data[0];
      var data = e.data[1];
      switch(eventName) {
        case 'setHeight':
          $iframe.height(data);
          break;
      }
    }, false);
    

    And inside the iframe, write a function to post the message:

    function resize() {
      var height = document.getElementsByTagName("html")[0].scrollHeight;
      window.parent.postMessage(["setHeight", height], "*"); 
    }
    

    Finally, inside the iframe, add an onLoad to the body tag to fire the resize function:

    <body onLoad="resize();">
    
    0 讨论(0)
提交回复
热议问题