我正在一个iframe中加载一个aspx网页。Iframe中的内容的高度可以超过iframe的高度。Iframe不应该有滚动条。
我在iframe里面有一个封装的div
标签,基本上就是所有的内容。 我写了一些jQuery来实现大小的调整。
$("#TB_window", window.parent.document).height($("body").height() + 50);
其中
TB_window
是包含Iframe
的div。
body
--iframe中aspx的body标签。
这个脚本被附加到iframe的内容上。我正在从父页面获得TB_window
元素。虽然这在Chrome上运行良好,但TB_window在Firefox上却崩溃了。我真的很困惑/不知道为什么会发生这种情况。
你可以使用IFRAME
'的内容的高度来检索。
contentWindow.document.body.scrollHeight
。
在 "IFRAME "加载完毕后,你可以通过以下方式改变高度。
<script type="text/javascript">
function iframeLoaded() {
var iFrameID = document.getElementById('idIframe');
if(iFrameID) {
// here you can make the height, I delete it first, then I make it again
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
}
</script>
然后,在IFRAME
标签上,你可以像这样挂上处理程序。
<iframe id="idIframe" onload="iframeLoaded()" ...
不久前我遇到一个情况,当表单提交后,我还需要从IFRAME
本身调用iframeLoaded
。你可以通过在IFRAME
的内容脚本中进行以下操作来实现。
parent.iframeLoaded();
对亚里士多德的回答略有改进...
<script type="text/javascript">
function resizeIframe(iframe) {
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
}
</script>
然后在你的iframe中声明如下。
<iframe onload="resizeIframe(this)" ...
有两个小的改进。
1.你不需要通过document.getElementById获得该元素--因为你已经在onload回调中获得了它。
2.2.如果你打算在下一条语句中重新分配iframe.height = ""
,就没有必要设置iframe.height = ""
。这样做实际上会产生开销,因为你要处理的是一个DOM元素。
编辑。 如果框架中的内容总是在变化,那么调用。
parent.resizeIframe(this.frameElement);
在更新后从iframe中调用。对同一原点有效。
或者自动检测。
// on resize
this.container = this.frameElement.contentWindow.document.body;
this.watch = () => {
cancelAnimationFrame(this.watcher);
if (this.lastScrollHeight !== container.scrollHeight) {
parent.resizeIframeToContentSize(this.frameElement);
}
this.lastScrollHeight = container.scrollHeight;
this.watcher = requestAnimationFrame(this.watch);
};
this.watcher = window.requestAnimationFrame(this.watch);
$(document).height() // - $('body').offset().top
和/或
$(window).height()
参见Stack Overflow问题https://stackoverflow.com/questions/806402。
试试这个方法,在jQuery中找到车身的高度。
if $("body").height()
如果Firebug,它没有一个值。也许这就是问题所在。