例如:
<iframe name="Stack" src="http://stackoverflow.com/" width="740"
frameborder="0" scrolling="no" id="iframe"> ...
</iframe>
我希望它能够根据其中的内容调整其高度,而无需使用滚动。
例如:
<iframe name="Stack" src="http://stackoverflow.com/" width="740"
frameborder="0" scrolling="no" id="iframe"> ...
</iframe>
我希望它能够根据其中的内容调整其高度,而无需使用滚动。
将此添加到您的<head>
部分:
<script>
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px';
}
</script>
并将您的 iframe 更改为:
<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />
正如在站点讨论中发现的那样。
您可以使用这个库,它既可以正确调整 iframe 的大小,也可以通过检测 iframe 内容的大小何时发生变化(通过定期检查 asetInterval
或 via MutationObserver
)并调整其大小来将其保持在正确的大小。
https://github.com/davidjbradshaw/iframe-resizer
他们也是 React 版本。
https://github.com/davidjbradshaw/iframe-resizer-react
这适用于跨域和同域 iframe。
这是一个紧凑的版本:
<iframe src="hello.html" sandbox="allow-same-origin"
onload="this.style.height=(this.contentWindow.document.body.scrollHeight+20)+'px';">
</iframe>
hjpotter92的建议在 safari 中不起作用!我对脚本做了一些小的调整,所以它现在也可以在 Safari 中使用了。
所做的唯一更改是在每次加载时将高度重置为 0,以使某些浏览器能够降低高度。
将此添加到<head>
标签:
<script type="text/javascript">
function resizeIframe(obj){
obj.style.height = 0;
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
并将以下onload
属性添加到您的 iframe,就像这样
<iframe onload='resizeIframe(this)'></iframe>
该hjpotter92答案的作品不够在某些情况下,但我发现iframe中的内容往往有底部裁剪在Firefox和IE浏览器,而精细的Chrome。
以下对我来说效果很好并修复了剪辑问题。该代码位于http://www.dyn-web.com/tutorials/iframes/height/。我做了一点修改,从 HTML 中取出 onload 属性。将以下代码放在<iframe>
HTML 之后和结束</body>
标记之前:
<script type="text/javascript">
function getDocHeight(doc) {
doc = doc || document;
// stackoverflow.com/questions/1145850/
var body = doc.body, html = doc.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
return height;
}
function setIframeHeight(id) {
var ifrm = document.getElementById(id);
var doc = ifrm.contentDocument? ifrm.contentDocument:
ifrm.contentWindow.document;
ifrm.style.visibility = 'hidden';
ifrm.style.height = "10px"; // reset to minimal height ...
// IE opt. for bing/msn needs a bit added or scrollbar appears
ifrm.style.height = getDocHeight( doc ) + 4 + "px";
ifrm.style.visibility = 'visible';
}
document.getElementById('ifrm').onload = function() { // Adjust the Id accordingly
setIframeHeight(this.id);
}
</script>
您的 iframe HTML:
<iframe id="ifrm" src="some-iframe-content.html"></iframe>
请注意,如果您更喜欢<head>
在文档中包含 Javascript,那么您可以恢复使用HTML 中的内联onload
属性iframe
,就像在dyn-web网页中一样。