【问题标题】:How to resize an external site to fit into an iframe?如何调整外部网站的大小以适应 iframe?
【发布时间】:2011-12-31 02:18:36
【问题描述】:

如何调整外部网站的大小以适应我网站中的 iframe? 请任何人帮助我?

【问题讨论】:

标签: html css


【解决方案1】:

)

如果外部 iframe 位于不同的域中,您将无法与它进行交互。如果它在同一个域中,您可以调整其内容的大小,如下所示:

/**
* this function allows you to retrieve the window object of an iframe given by its ID
* 
* @param {string} id - iframe id
*/
var getIframe = function (id) {
    if ($.browser.mozilla) return document.getElementById(id).contentWindow;
    return window.frames[id];
};

然后,从外部文件(包含 iframe 的文件)中,您可以在加载 iframe 时调用如下内容:

var resizeIframeContent = function(iframeID, sizeX, sizeY){

  var iframe = getIframe(iframeID);
  iframe.updateSize(sizeX, sizeY);

}

使用此代码,您在 iframe 的内部文档中调用函数 updateSize,因此您应该将此函数添加到附加到窗口对象(全局命名空间)的嵌套文档中。像这样的:

var updateSize= function(sizeX, sizeY){
   //do you resizing stuff here, which depends on your html structure, it could be something like this:
    $("#content").width(sizeX).height(sizeY);
}

但是,我认为您的问题是错误的,您实际上是想问如何修改 iframe(而不是 iframe 内容)的大小以适应其内部内容。如果是这样,你不能在跨域的情况下这样做,但如果两个页面都在同一个域中,你可以用类似的方式来做,像这样:

在您的内部文档上,当文档准备好时,将其大小发送到父容器:

$(function(){
  var content = $("#content"); //change this to point your container, or obtain the document height or anything else
  parent.onIframeDimensionsRetrieved( content.width(), content.width() );
});

并在您的外部文档(带有 iframe 的文档)中检索新尺寸并更新 iframe 尺寸:

var onIframeDimensionsRetrieved = function(width ,height){
   $("#youriframe").width(width).height(height);
}

就是这样 :-) 我所有的示例代码都使用 jQuery 来使其具有可读性,如果您愿意,也可以使用纯 JS 来实现。

祝你好运!我希望它有所帮助:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多