在 iframe 中:
这意味着您必须在 iframe 页面中添加一些代码。
只需将此脚本添加到 IFRAME 中的代码:
<body onload="parent.alertsize(document.body.scrollHeight);">
在保留页面中:
在包含 iframe 的页面中(在我的情况下 ID="myiframe")添加一个小 javascript:
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
现在发生的情况是,当 iframe 被加载时,它会在父窗口中触发一个 javascript,在本例中是包含 iframe 的页面。
向该 JavaScript 函数发送其(iframe)高度的像素数。
父窗口获取数字,向其添加 32 以避免滚动条,并将 iframe 高度设置为新数字。
就是这样,不需要其他任何东西。
但如果您想了解更多小技巧,请继续阅读......
iframe 中的动态高度?
如果您像我一样喜欢切换内容,则 iframe 高度会发生变化(无需重新加载页面并触发 onload)。
我通常添加一个我在网上找到的非常简单的切换脚本:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
}
</script>
只需在该脚本中添加:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>
如何使用上面的脚本很简单:
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
对于那些喜欢剪切和粘贴然后从那里开始的人来说,这里有两页。就我而言,我将它们放在同一个文件夹中,但它也应该跨域工作(我认为......)
完整的控股页面代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>
<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>
完整的 iframe 代码:(此 iframe 名为“theiframe.htm”)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight);
}
</script>
</head>
<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END
</body>
</html>
Demo