我正在尝试调整 iframe 的大小以适应内容。在看到其他人如何做到这一点后,我认为最简单的方法是获取 iframe 的滚动高度并相应地调整 iframe 的大小。我在 iframe 标记中使用 onload 来运行它。我围绕这个主题创作了几十个变体,但都没有成功。
function resizeIFrame(){
var sHeight, frame;
frame = document.getElementById("bigFrame");
sHeight = frame.scrollHeight;
frame.style.height = sHeight + 'px';
}
当我警告 sHeight 变量时,我得到的是框架的高度,而不是滚动高度。这表明我可能没有正确收集滚动高度。
我知道这个问题可能与以前的许多问题相似,但有很多方法可以解决这个问题,并且有更多种类的答案。我想知道这种调整 iframe 大小以适应内容的方法有什么问题吗?
这是 html。
<div id="contentContainer">
<iframe id="bigFrame"
src="home/home.html"
name="mainFrame"
onload="resizeIFrame()"
onresize="resizeIFrame()"
scrolling="no"
seamless; >
</iframe>
</div>
好吧,我让它完美地工作了。
添加 - contentWindow.document.body.scrollHeight - 使我能够获得滚动高度。我试图从变量中获取滚动高度。这不起作用。有效的方法是直接从文档中获取滚动高度。
我必须在每页底部添加一些空间。因此+80;。不幸的是,每次调用该函数时,这只增加了 80。在重新调整之前将框架高度重置为 0px 解决了问题。
就这样吧。该函数通过获取scrollHeight 并设置iframe 高度来匹配,从而调整iframe 的大小以适应其内容。
function resizeIFrame(){
var sHeight, frame;
frame = document.getElementById("bigFrame");
frame.style.height = '0px';
sHeight = document.getElementById('bigFrame').
contentWindow.document.body.scrollHeight + 80;
frame.style.height = sHeight + 'px';
}
尝试使用
frame.style.height = sHeight + 'px';
接受的答案很不错,但它提到高度不太正确。我通过依赖
html
节点 scrollHeight
而不是主体的(即其父节点)来修复。
sHeight = iframe.contentWindow.document.body.parentNode.scrollHeight;