Make iframe automatically adjust height according

2018-12-31 10:14发布

This question already has an answer here:

For example:

<iframe name="Stack" src="http://stackoverflow.com/" width="740"
        frameborder="0" scrolling="no" id="iframe"> ...
</iframe>

I want it to be able to adjust its height according to the contents inside it, without using scroll.

17条回答
呛了眼睛熬了心
2楼-- · 2018-12-31 11:05

I've had problems in the past calling iframe.onload for dynamically created iframes, so I went with this approach for setting the iframe size:

iFrame View

var height = $("body").outerHeight();
parent.SetIFrameHeight(height);

Main View

SetIFrameHeight = function(height) {
    $("#iFrameWrapper").height(height);
}

(this is only going to work if both views are in the same domain)

查看更多
墨雨无痕
3楼-- · 2018-12-31 11:06

Avoid inline JavaScript; you can use a class:

<iframe src="..." frameborder="0" scrolling="auto" class="iframe-full-height"></iframe>

And reference it with jQuery:

$('.iframe-full-height').on('load', function(){
    this.style.height=this.contentDocument.body.scrollHeight +'px';
});
查看更多
裙下三千臣
4楼-- · 2018-12-31 11:08

Try this for IE11

<iframe name="Stack" src="http://stackoverflow.com/" style='height: 100%; width: 100%;' frameborder="0" scrolling="no" id="iframe">...</iframe>
查看更多
旧时光的记忆
5楼-- · 2018-12-31 11:08
<script type="text/javascript">
  function resizeIframe(obj) {
    obj.style.height = 0;
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>

this is not working for chrome. But working for firefox.

查看更多
泪湿衣
6楼-- · 2018-12-31 11:10

You can use this library, which both initially sizes your iframe correctly and also keeps it at the right size by detecting whenever the size of the iframe's content changes (either via regular checking in a setInterval or via MutationObserver) and resizing it.

https://github.com/davidjbradshaw/iframe-resizer

This works with both cross and same domain iframes.

查看更多
登录 后发表回答