Adjust Height of iFrame When New Content is Loaded

扶醉桌前 提交于 2019-12-25 16:26:08

问题


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>

回答1:


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.

  • how to properly display an iFrame in mobile safari
  • https://encrypted.google.com/search?q=iframe+resize+ios+issue

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.




回答2:


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';
      }


来源:https://stackoverflow.com/questions/28334453/adjust-height-of-iframe-when-new-content-is-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!