What are the methods for adapting the height of an iframe dynamically?

There are several ways to achieve auto-adjusting the height of an iframe:

  1. Dynamically adjusting height with JavaScript: Use JavaScript to get the actual height of the content in the iframe, then assign that height to the iframe’s height attribute.
<script>
  function resizeIframe() {
    var iframe = document.getElementById('myIframe');
    var iframeHeight = iframe.contentWindow.document.body.scrollHeight;
    iframe.style.height = iframeHeight + 'px';
  }
</script>

<iframe id="myIframe" src="yourPage.html" onload="resizeIframe()"></iframe>
  1. Using the CSS calc() function: Calculate the height of the iframe using the CSS calc() function by setting it to 100% minus a fixed height.
<style>
  #myIframe {
    height: calc(100% - 50px); /* 50px为固定高度 */
  }
</style>

<iframe id="myIframe" src="yourPage.html"></iframe>
  1. Use the jQuery resize() method to automatically adjust the height of the iframe.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function() {
    $('#myIframe').on('load', function() {
      $(this).height($(this).contents().height());
    });
  });
</script>

<iframe id="myIframe" src="yourPage.html"></iframe>
bannerAds