例如:
<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>
我希望它能够根据里面的内容来调整它的高度,而不使用滚动。
当前回答
<script type="text/javascript">
function resizeIframe(obj) {
obj.style.height = 0;
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
这是不工作的chrome。但是在firefox上工作。
其他回答
这适用于我(也与多个iframe在一个页面):
$('iframe').load(function(){$(this).height($(this).contents().outerHeight());});
我在过去调用iframe时遇到过问题。onload用于动态创建iframe,所以我用这种方法来设置iframe大小:
iFrame视图
var height = $("body").outerHeight();
parent.SetIFrameHeight(height);
主要的观点
SetIFrameHeight = function(height) {
$("#iFrameWrapper").height(height);
}
(这只会工作,如果两个视图在同一个域)
function autoResize(id){
var newheight;
var newwidth;
if(document.getElementById){
newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;
}
document.getElementById(id).height=(newheight) + "px";
document.getElementById(id).width=(newwidth) + "px";
}
把这个添加到你的iframe: onload = " autoResize (youriframeid)”
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>
您可以使用这个库,它既能正确地调整iframe的初始大小,也能通过检测iframe内容的大小变化(通过setInterval中的常规检查或通过MutationObserver)并调整它来保持它在正确的大小。
https://github.com/davidjbradshaw/iframe-resizer
他们也是一个React版本。
https://github.com/davidjbradshaw/iframe-resizer-react
这适用于交叉和相同域的iframe。