任何人都可以告诉我正在尝试在 iframe onload 函数中加载 url 吗?我想显示没有滚动条的 iframe 并调整其内容,但父页面将根据内容滚动任何人都可以告诉如何调整 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";
}
}
}
关于javascript - 如何调整跨域url中iframe的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37019790/