使用 Jquery 将 iframe 调整为内容的大小



我正在尝试动态调整iframe的大小以适应其内容。为此,我有一段代码:

$("#IframeId").height($("#IframeId").contents().find("html").height());​

它不起作用。是因为跨域问题吗?我怎样才能让它适合?请看一下小提琴:JsFiddle

ps 我已经设置了链接的 html 和正文height:100%;

你只需要在 iframe load 事件上应用你的代码,所以当时已经知道高度了,代码如下:

$("#IframeId").load(function() {
    $(this).height( $(this).contents().find("body").height() );
});

请参阅工作演示。这个演示适用于 jsfiddle,因为我已将 iframe url 设置为与 jsfiddle 结果 iframe 位于同一域中的网址,即fiddle.jshell.net域。

更新:
@Youss:似乎您的页面出于某种奇怪的原因没有获得正确的正文高度,因此请尝试使用主要元素的高度,如下所示:

$(document).ready(function() {
    $("#IframeId").load(function() {
            var h = $(this).contents().find("ul.jq-text").height();
            h += $(this).contents().find("#form1").height();
            $(this).height( h );
        });
});

不知道为什么@Nelson的解决方案在Firefox 26(Ubuntu)中不起作用,但以下Javascript-jQuery解决方案似乎适用于Chromium和Firefox。

/**
 * Called to resize a given iframe.
 *
 * @param frame The iframe to resize.
 */
function resize( frame ) {
  var b = frame.contentWindow.document.body || frame.contentDocument.body,
      cHeight = $(b).height();
  if( frame.oHeight !== cHeight ) {
    $(frame).height( 0 );
    frame.style.height = 0;
    $(frame).height( cHeight );
    frame.style.height = cHeight + "px";
    frame.oHeight = cHeight;
  }
  // Call again to check whether the content height has changed.
  setTimeout( function() { resize( frame ); }, 250 );
}
/**
 * Resizes all the iframe objects on the current page. This is called when
 * the page is loaded. For some reason using jQuery to trigger on loading
 * the iframe does not work in Firefox 26.
 */
window.onload = function() {
  var frame,
      frames = document.getElementsByTagName( 'iframe' ),
      i = frames.length - 1;
  while( i >= 0 ) {
    frame = frames[i];
    frame.onload = resize( frame );
    i -= 1;
  }
};

这会不断调整给定页面上所有 iframe 的大小。

使用 jQuery 1.10.2 进行测试。

使用$('iframe').on( 'load', ...只会间歇性地工作。请注意,如果要在某些浏览器中缩小到默认iframe高度以下,则大小最初必须设置为 0 像素的高度。

您可以执行以下操作:

  • 在 iFrame 中使用 document.parent.setHeight(myheight) 将 iFrame 内的高度设置为父级。这是允许的,因为它是子控件。从父级调用函数。

  • 在父级中,你创建了一个函数setHeight(iframeheight),用于调整iFrame的大小。

另请参阅:
如何使用 Javascript 从 Iframe 实现跨域 URL 访问?

只需在 HTML 标签上执行此操作,即可完美运行

$("#iframe").load(function() {
    $(this).height( $(this).contents().find("html").height() );
});

由于问题的答案使用已经过时的jquery(load已被弃用并替换为.on('load',function(){}),下面是问题中答案的最新代码。

请注意,我使用 scrollHeight 和 scrollWidth,我认为它们比使用高度和宽度加载得更好,就像提供的答案一样。它将完全适合,不再滚动。

$("#dreport_frame").on('load',function(){
  var h = $('#dreport_frame').contents().find("body").prop('scrollHeight');
  var w = $('#dreport_frame').contents().find("body").prop('scrollWidth');
  $('#dreport_frame').height(h);
  $('#dreport_frame').width(w);
})

加载时调整 iframe 的高度,并根据其主体高度调整大小。

var iFrameID = document.getElementById('iframe2');
var iframeWin = iFrameID.contentWindow;
var eventList = ["load", "resize"];
for(event of eventList) {
    iframeWin.addEventListener(event, function(){ 
        if(iFrameID) {
            var h = iframeWin.document.body.offsetHeight  + "px";
            if(iFrameID.height == h) {
                return false;
            }
            iFrameID.height = "";
            iFrameID.height = iframeWin.document.body.offsetHeight  + "px";
        }   
    })  
} 

最后,我附带了这个跨域解决方案,它也适用于调整大小......(调整大小不触发:当 iframe 内容的高度更改时自动调整 iframe 高度(同一域) )

Iframe :

(function() {
    "use strict";
    var oldIframeHeight = 0,
        currentHeight = 0;
    function doSize() {
        currentHeight = document.body.offsetHeight || document.body.scrollHeight;
        if (currentHeight !== oldIframeHeight) {
            console.log('currentHeight', currentHeight);
            window.parent.postMessage({height:currentHeight}, "*");
            oldIframeHeight = currentHeight;
        }
    }
    if (window.parent) {
        //window.addEventListener('load', doSize);
        //window.addEventListener('resize', doSize); 
        window.setInterval(doSize, 100); // Dispatch resize ! without bug
    }
})();

父页面 :

window.addEventListener('message', event => {
    if (event.origin.startsWith('https://mysite.fr') && event.data && event.data.height)  {
        console.log('event.data.height', event.data.height);
        jQuery('#frameId').height(event.data.height + 12);
    }
});

最新更新