如何根据其内容的高度调整iframe的高度?

时间:2019-09-15 06:47:57

标签: javascript html css iframe flexbox

如何根据其内容的高度调整iframe的高度?我已经阅读了stackoverflow中的其他答案。但是这些答案对我没有用。我在index.html中有3个iframe。我想调整ID为myIframe的第二个iframe的高度。这是我的index.html(该代码在Internet Explorer中有效,但在chrome和firefox中无效):

<!DOCTYPE html>

<html>

<body>

<div style="display: flex; flex-direction: column; align-items: stretch;">

<iframe src="header.html" scrolling="no" style="width: 100%;border: 0; 
height:50px"></iframe>


<iframe class="" id="myIframe" onload = "changeheight()" 
name="a" scrolling="no" style="border:none; width: 100%; min- 
height:calc(100vh - 115px);"  allowtransparency="true" allowfullscreen>

</iframe>

<iframe src="footer.html" scrolling="no" style="width: 100%;border: 0; 
height:50px;"></iframe>


</div>

<script type='text/javascript'>


function changeheight() {

document.getElementById('myIframe').style.height =
document.getElementById('myIframe').contentWindow.document.body.scrollHeight 
+ 'px';
}

</script>


</body>

</html>

我的header.html是

<!DOCTYPE html>

<html>

<body>


<header style="padding: 20px; background: pink">

<a target="a" href="about.html">About us</a>
<a target="a" href="contact.html">Contact us</a>

</header>

</body>

</html>

about.html和contact.html包含一些虚拟数据。

我在控制台的chrome中遇到了这两个错误-

index.html:22 Uncaught ReferenceError: changeheight is not defined
at HTMLIFrameElement.onload (index.html:22)

index.html:82 Uncaught DOMException: Blocked a frame with origin "null" from 
accessing a cross-origin frame.

我不明白为什么会遇到第一个错误。我已经在javascript中定义了changeheight。

我根本不理解第二个错误。

1 个答案:

答案 0 :(得分:1)

两个问题

  1. 您需要将脚本移至iframe上方

  2. 您需要实际加载一些内容(将src =“ someURL”添加到您要使用的iframe中)

see this glitch

相关问题