主窗口和iframe都位于同一个域中,但我想要实现的是调整iframe以仅在iframe中使用js来调整其内容。
我也不知道主窗口分配给它的iframe的id。而且我不想使用jquery或任何其他框架。
主窗口和iframe都位于同一个域中,但我想要实现的是调整iframe以仅在iframe中使用js来调整其内容。
我也不知道主窗口分配给它的iframe的id。而且我不想使用jquery或任何其他框架。
你也可以在不知道的情况下做到这一点 id
的 iframe
在父窗口中:
window.frameElement.style.width = iframeContentWidth + 'px';
window.frameElement.style.height = iframeContentHeight + 'px';
看到 frameElement
在 MDN。
编辑
以防万一 iframe
恰好位于具有固定大小的容器元素中 overflow: hidden
你可以这样做:
function resizeIframe (iframeContentWidth, iframeContentHeight) {
var container = window.frameElement.parentElement;
if (container != parent.document.body) {
container.style.width = iframeContentWidth + 'px';
container.style.height = iframeContentHeight + 'px';
}
window.frameElement.style.width = iframeContentWidth + 'px';
window.frameElement.style.height = iframeContentHeight + 'px';
return;
}
对于像你这样的同源内容, 是的你可以。
借用加里对上述问题的回答:
在iframe中,window.parent引用父对象的全局对象 文档,而不是文档对象本身。我相信你需要 使用parent.document.getElementById
尝试使用parent.document访问iframe,看看这是否解决了您的问题。
假设您在主窗口中只有1个IFRAME,则可以从IFRAME文档的Javascript中执行以下操作:
function getMySelf()
{
return (window.parent.document.getElementsByTagName("iframe"))[0];
}
var myself = getMySelf();
myself.style.width = whateverWidth;
myself.style.height = whateverHeight;