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

时间:2012-10-13 10:51:12

标签: javascript jquery iframe

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

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

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

ps我已经设置了链接height:100%;

的html和正文

7 个答案:

答案 0 :(得分:15)

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

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

见工作demo。这个演示在jsfiddle上运行,因为我已将iframe网址设置为与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 );
        });
});

答案 1 :(得分:4)

不确定为什么@ 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', ...只能间歇性地工作。请注意,如果要在某些浏览器中缩小到默认0高度以下,则尺寸最初必须设置为iframe像素高度。

答案 2 :(得分:3)

您可以做的是:

  • 在iFrame中使用document.parent.setHeight(myheight)将iFrame中的高度设置为父级。这是允许的,因为它是儿童控制。从父母那里调用一个函数。

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

另见:
How do I implement Cross Domain URL Access from an Iframe using Javascript?

答案 3 :(得分:2)

只需在HTML标记上执行此操作即可,

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

答案 4 :(得分:1)

作为问题的答案,请使用已经过时的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);
})

答案 5 :(得分:0)

Adjust height of an iframe, on load and resize, based on its body height.

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

        }   
    })  
} 

答案 6 :(得分:0)

最后,我带来了这个跨域解决方案,它也适用于调整大小... (调整大小不触发:Auto resize iframe height when the height of the iframe contents change (same domain)

内嵌框架:

(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);
    }
});
相关问题