iFrame动态调整大小

iFrame dynamic resize

本文关键字:调整 动态 iFrame      更新时间:2023-09-26

我有这个代码,但不工作…iFrame不会根据内容来调整大小…

我做错了什么?我已经尝试了很多代码,任何人都在为我工作……

有什么建议吗?

page.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TEST</title>
</head>
<body>
    <iframe id="klaus" src="iframe.html" width="960" height="100%"></iframe>
</body>
</html>

iframe.html

<!DOCTYPE html>
<html>
<head>
<title>pagina</title>
<script language="Javascript" type="text/javascript">
  parent.document.getElementById("klaus").height = document.getElementById("size").scrollHeight + 40;
</script>
</head>
<body>
<div id="size">
<p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p>
<p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p>
<p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p>
<p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p>
<p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p>
<p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p>
<p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p>
<p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p>
<p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p>
<p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p> <p>Conteudo</p>
</div>
</body>
</html>

我想这会对你有帮助,把这个块放在iframe.html页面的末尾,然后删除你的块。

<script language="Javascript" type="text/javascript">
  var _iframe = parent.document.getElementById("klaus"),
      _height = _iframe.contentDocument.getElementById("size").scrollHeight || _iframe.contentWindow.document.getElementById("size").scrollHeight;
      _iframe.height = _height + 40;
</script>

iframe从不根据其内容调整大小。您需要使用javascript来实现这一点。你的百分比样式值将总是引用iframe最靠近位置的父元素,就像大多数其他元素一样。

这个问题展示了如何使用脚本:

调整iframe的宽度和高度以适应其中的内容

您设置的高度属性错误。在高度之前缺少样式。此外,javascript代码没有被调用,我将其添加到一个函数中,该函数在页面的onload中调用。检查代码:

<title>pagina</title>
<script language="Javascript" type="text/javascript">
function resizeIframe(){  
parent.document.getElementById("klaus").style.height = document.getElementById("size").scrollHeight + 40;
}
</script>
</head>
<body onload="resizeIframe()">