【发布时间】:2016-05-04 06:11:06
【问题描述】:
任何人都可以告诉我正在尝试在 iframe onload 函数中加载 url。我想在没有滚动条的情况下显示 iframe 并调整其内容,但父页面将根据内容滚动任何人都可以告诉我如何调整 iframe 的大小跨域网址?
谢谢
【问题讨论】:
标签: javascript angularjs iframe
任何人都可以告诉我正在尝试在 iframe onload 函数中加载 url。我想在没有滚动条的情况下显示 iframe 并调整其内容,但父页面将根据内容滚动任何人都可以告诉我如何调整 iframe 的大小跨域网址?
谢谢
【问题讨论】:
标签: javascript angularjs iframe
为了根据内容调整 iframe 的大小,您不能使用 postMessage 将当前 iframe 高度发送给其父级。
包含在 iFrame 中的页面需要使用 postMessage 将其当前高度发送到包含页面。 包含页面必须监听该消息并相应地更改 iframe 的高度。
包含页面中的代码可能如下所示:
function getBottom() {
var max = jQuery("body").height();
//Your additional calculations go here
return max;
}
function updateHeight() {
sendHeightToParent();
setTimeout(updateHeight, 500);
}
function sendHeightToParent() {
var messageObject = {
"type":"size",
"version":"1.0.0",
"params":{
"height": getBottom()
}
};
//YOURTARGET is the target page if known. Otherwise use "*"
parent.postMessage(JSON.stringify(messageObject), "YOURTARGET");
}
//Only possible if html5 post message is available
if (typeof parent.postMessage == 'function') {
jQuery().ready(function() {
sendHeightToParent();
setTimeout(updateHeight, 500);
});
}
然后父级监听事件并相应地更新 iframe:
//Only possible if html5 post message is available
if (typeof parent.postMessage == 'function') {
window.addEventListener("message", function (e) {
obj = JSON.parse(e.data);
if (obj.type == 'size') {
myFrame = document.getElementById('YouIFrameId');
myFrame.stye.height = obj.params.height + "px";
}
}
}
【讨论】: