This question already has an answer here: 这个问题已经在这里有了答案:
For example: 例如:
<iframe name="Stack" src="http://stackoverflow.com/" width="740"
frameborder="0" scrolling="no" id="iframe"> ...
</iframe>
I want it to be able to adjust its height according to the contents inside it, without using scroll. 我希望它能够根据其中的内容调整高度,而无需使用滚动。
#1楼
参考:https://stackoom.com/question/frAA/使iframe无需使用滚动条即可根据内容自动调整高度-重复
#2楼
The suggestion by hjpotter92 does not work in safari! hjpotter92的建议在野生动物园中不起作用! I have made a small adjustment to the script so it now works in Safari as well. 我对该脚本做了一些小的调整,因此它现在也可以在Safari中使用。
Only change made is resetting height to 0 on every load in order to enable some browsers to decrease height. 为了使某些浏览器降低高度,唯一的改变就是在每次加载时将高度重置为0。
Add this to <head>
tag: 将此添加到<head>
标签:
<script type="text/javascript">
function resizeIframe(obj){
obj.style.height = 0;
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
And add the following onload
attribute to your iframe, like so 并将以下onload
属性添加到您的iframe中,如下所示
<iframe onload='resizeIframe(this)'></iframe>
#3楼
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";
}
add this to your iframe: οnlοad="autoResize('youriframeid')" 将此添加到您的iframe:onload =“ autoResize('youriframeid')”
#4楼
You can use this library, which both initially sizes your iframe correctly and also keeps it at the right size by detecting whenever the size of the iframe's content changes (either via regular checking in a setInterval
or via MutationObserver
) and resizing it. 您可以使用此库,该库不仅可以正确地调整iframe的大小,而且还可以通过检测iframe内容的大小是否发生变化(通过定期检查setInterval
或MutationObserver
)并调整大小来保持其正确大小。
https://github.com/davidjbradshaw/iframe-resizer https://github.com/davidjbradshaw/iframe-resizer
Their is also a React version. 它们也是React版本。
https://github.com/davidjbradshaw/iframe-resizer-react https://github.com/davidjbradshaw/iframe-resizer-react
This works with both cross and same domain iframes. 这适用于跨域和相同域的iframe。
#5楼
I've had problems in the past calling iframe.onload for dynamically created iframes, so I went with this approach for setting the iframe size: 过去在为动态创建的iframe调用iframe.onload时遇到了问题,因此我采用了这种方法来设置iframe大小:
iFrame View iFrame视图
var height = $("body").outerHeight();
parent.SetIFrameHeight(height);
Main View 主视图
SetIFrameHeight = function(height) {
$("#iFrameWrapper").height(height);
}
(this is only going to work if both views are in the same domain) (这仅在两个视图都在同一域中时才起作用)
#6楼
<script type="text/javascript">
function resizeIframe(obj) {
obj.style.height = 0;
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
this is not working for chrome. 这不适用于Chrome。 But working for firefox. 但是为Firefox工作。