【问题标题】:How to make dynamic iFrame height?如何制作动态 iFrame 高度?
【发布时间】:2013-11-13 17:35:23
【问题描述】:

我正在尝试制作动态 iFrame 高度以适应页面内容。

我有两页。 index.php 和 example.html

我在“index.php”中插入“example.html”作为iFrame,“example.html”中的内容高度是可变的。

这是我在“index.php”中的代码

<iframe src="example.html" name="iframe1" id="myiframe" marginwidth="0"
marginheight="0" align="top" scrolling="no" width="100%" height="auto" frameborder="0">
</iframe>

<script type="text/javascript">
var f = document.getElementById("myiframe");
f.onload = function() {
  this.style.height = this.contentWindow.document.body.offsetHeight + "40px";
}
</script>

我的 CSS:

#myiframe {
margin: auto;
padding: 0px;
float: left;
height: auto;
min-height: 255px;
height: auto !important;        /* for IE as it does not support min-height */
height: 255px;                   /* for IE as it does not support min-height */
width: 100%;
}

iFrame 工作正常,但动态高度根本不起作用。有什么建议么?谢谢。

【问题讨论】:

  • 两个页面是否在同一个域中?是否有任何 JavaScript 安全警告?
  • 是的,它们都在线托管在相同的域和路径上。 @grimmus
  • 你用的是什么浏览器? iframe onload() 对不同浏览器的支持质量参差不齐。例如,请参阅stackoverflow.com/questions/12910534/…
  • 其实我只在 Chrome 和 Mozilla 上测试过 @axel_c
  • 我会在iframe 内做something like this

标签: javascript php html css iframe


【解决方案1】:

你可以使用jquery,可以使用$(window).height();

<iframe src="example.html" width="100%" class="myIframe">
<p>Hi</p>
</iframe>

<script type="text/javascript" language="javascript"> 
$('.myIframe').css('height', $(window).height()+'px');
</script>

【讨论】:

    【解决方案2】:

    使用 jQuery,将其放置在父页面中。

    $('iframe').load(function () {
        $(this).height($(this).contents().height());
        $(this).width($(this).contents().width());
    });
    

    如果它们是不同的子域,您需要将其添加到父页面和 iframe 页面:

        document.domain = "shareddomain.com"
    

    【讨论】: