Adjust Height of iFrame When New Content is Loaded

2019-09-06 01:22发布

I have an iFrame that is included in my HTML and is available when the page loads. When the page first loads, the iFrame has no content/src. I am using jQuery to insert content into the iFrame dynamically. When a user clicks a link on my page, the contents of the iFrame are updated. All of this is working for me. However, I am struggling to adjust the height of the iFrame when new content is loaded. I have tried several solutions on StackOverflow but with no success. Here is my iFrame code:

<iframe id="myframe" width="100%" frameborder="0"></iframe>

Here is my jQuery that changes the HTML inside of my iFrame:

emailOpened.find('#myframe').contents().find('body').html(email.body);

This works for me. I just need my iFrame to adjust its height based on the height of the content being injected. I have failed on all attempts with this part.

Any help is appreciated!

UPDATE:

Here is my new HTML:

<iframe id="myframe" width="100%" frameborder="0">
  <body onload="parent.resizeIframe(document.body.scrollHeight);">
</iframe>

2条回答
三岁会撩人
2楼-- · 2019-09-06 01:54

If you need mobile support and allow (user) scrolling for the iframe check out https://github.com/davidjbradshaw/iframe-resizer a as drop-in solution which fixes different issues on iOS and android.

I had to support mobile devices as well and ended up using it after some hours of research and testing. I've also used the provided message channel to send messages to the inner document back and forth.

查看更多
相关推荐>>
3楼-- · 2019-09-06 02:10

Call this function directly after the html has been changed.

      function resizeIframe() {
          var newHeight = document.getElementById('myframe').contentDocument.body.scrollHeight;
          document.getElementById('myframe').style.height = parseInt(newHeight,10) + 10 + 'px';
      }
查看更多
登录 后发表回答