javascript 根据内部动态内容更改 iframe 高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12826852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change iframe height based on dynamic content inside
提问by Steven
Possible Duplicate:
Resizing an iframe based on content
可能的重复:
根据内容调整 iframe 的大小
I'm trying to load one of my pages into an iframe. I'm never sure how big the page will be, the data on the page is loaded dynamically. I'd like the iframe to always fit the page, no matter how big or small it is. Here's what I have:
我正在尝试将其中一个页面加载到 iframe 中。我永远不确定页面有多大,页面上的数据是动态加载的。我希望 iframe 始终适合页面,无论它有多大。这是我所拥有的:
function loadModal() {
myframe = $('<iframe id="mymodal" src="MyPage.aspx" width="700"></iframe>');
myframe.appendTo($('html'));
var height = document.getElementById('modalPreview').contentWindow
.document.body.scrollHeight;
$("#mymodal").attr("height", height);
}
I've been trying to get the height of the page after it's loaded. The problem is that height
comes back as 0
. But if I do this:
我一直在尝试获取页面加载后的高度。问题是height
作为0
. 但如果我这样做:
setTimeout(function () {
$("#mymodal").attr("height", height);
}, 2000);
the correct height is loaded. I assume it's because the data needs a few seconds to load. But this looks funky if the page loads really fast, or it will still give me a height of 0 if it takes more than 2 seconds to load the page.
加载了正确的高度。我认为这是因为数据需要几秒钟才能加载。但是,如果页面加载速度非常快,这看起来很奇怪,或者如果加载页面超过 2 秒,它仍然会给我 0 的高度。
So is there a way to:
那么有没有办法:
- Wait and set the height of the iframe once the data loads, or
- Set the height of the parent iframe from
MyPage.aspx
?
- 等待并在数据加载后设置 iframe 的高度,或者
- 从
MyPage.aspx
?设置父 iframe 的高度
回答by Matt K
If you're going to use option #2 you can access the parent window using the DOM and set the iframe height from the child.
如果您打算使用选项 #2,您可以使用 DOM 访问父窗口并设置子窗口的 iframe 高度。
$(document).ready(function() {
var iframeWin = parent.document.getElementById("yourIframeID");
iframeWin.height = document.body.scrollHeight;
});
回答by Diodeus - James MacFarlane
You can hook an onload
event to the Iframe
before you insert it. When it fires, inspect the height of the document in the iframe and adjust its height accordingly.
您可以在插入onload
事件Iframe
之前将其挂接到。当它触发时,检查 iframe 中文档的高度并相应地调整其高度。