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

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

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

它不起作用。 是因为跨域问题吗? 我如何使它适合? 请看看Fiddle: JsFiddle

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

您只需要在iframe load事件上应用代码,因此当时已知高度,代码如下:

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

看工作演示 。 这个演示适用于jsfiddle,因为我已经将iframe url设置为与jsfiddle结果iframe在同一域中的url,即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中的高度设置为父级。 这是允许的,因为它是儿童控制。 从父级调用函数。

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

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

只需在HTML标签上进行,就可以完美运行

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

根据身高调整iframe的高度,加载和resize。

 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"; } }) } 

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

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

 $("#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); })