如何制作动态iFrame高度?

时间:2013-11-13 17:35:24

标签: javascript php html css iframe

我正在尝试制作动态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工作正常,但动态高度根本不起作用。有什么建议?感谢。

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

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

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

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

    document.domain = "shareddomain.com"
相关问题