如何根据内容的大小“增长”iFrame?

问题描述:

我正在动态加载iFrame,有些页面比其他页面“更高”。我希望iFrame能够相应增长。可能吗?如果是这样,怎么样?如何根据内容的大小“增长”iFrame?

是的,这是可能的jQuery。 父页代码:

<iframe id='ifrm' /> 

脚本的iframe页上:回发后

function alertSize() { 
    var myHeight = 0; 
    if (typeof (parent.window.innerWidth) == 'number') { 
    //Non-IE 
    myHeight = parent.window.innerHeight; 
    } else if (parent.document.documentElement 
    && (parent.document.documentElement.clientWidth || parent.document.documentElement.clientHeight)) { 
    //IE 6+ in 'standards compliant mode' 
    myHeight = parent.document.documentElement.clientHeight; 
    } else if (parent.document.body && (parent.document.body.clientWidth || parent.document.body.clientHeight)) { 
    //IE 4 compatible 
    myHeight = parent.document.body.clientHeight; 
    } 
    //window.alert('Height = ' + myHeight); 
    return myHeight; 
} 

function AssignFrameHeight() { 
    var theFrame = $("#ifrm", parent.document.body); 
    var frameHeight1 = getIframeHeight('ifrm'); 
    var frameHeight2 = $(document.body).height(); 
    if ($(document.body)[0]) { 
    if ($(document.body)[0].bottomMargin) 
     frameHeight2 += Number($(document.body)[0].bottomMargin); 
    if ($(document.body)[0].topMargin) 
     frameHeight2 += Number($(document.body)[0].topMargin); 
    } 
    if (frameHeight1 > frameHeight2) { 
    theFrame.height(frameHeight1 - 20); 
    } else { 
    if ($.browser.msie) 
     theFrame.height(frameHeight2); 
    else 
     theFrame.height(frameHeight2 + 50); 
    } 
} 

function getIframeHeight(iframeName) { 
    //var iframeWin = window.frames[iframeName]; 
    var iframeEl = parent.document.getElementById 
    ? parent.document.getElementById(iframeName) 
    : parent.document.all 
     ? parent.document.all[iframeName] 
     : null; 
    if (iframeEl) { 
    iframeEl.style.height = "auto"; // helps resize (for some) if new doc shorter than previous 
    //var docHt = getDocHeight(iframeWin.document); 
    // need to add to height to be sure it will all show 
    var h = alertSize(); 
    //var new_h = (h - 148); 
    //iframeEl.style.height = h + "px"; 
    return h; 
    //alertSize(); 
    } 
} 

重新分配高度:

function pageLoad() { // MS AJAX - UpdatePanel 
    AssignFrameHeight(); 
} 

$(document).ready(function() { // jQuery 
    AssignFrameHeight(); 
}); 
+2

不错。加载浏览器黑客;) – naugtur 2010-05-20 12:06:25

+0

适用于:IE 4-8,FF 3,Opera 10,Chrome 4.0,Safari(最新版本) – VMAtm 2010-05-20 12:15:26

+0

拯救生命!谢谢 – bladefist 2011-11-12 18:40:17

你也许可以做到像

document.getElementById('your-iframe').height=new_height; 

但如果你真的需要有一个iframe根据内容能够生长,那么我建议你尝试另一个HTML元素作为一个iframe可能不是你所需要的。

尝试使用宽度:100%;身高:100%并将它们应用于您的iframe元素

+1

它不会工作。你必须从字面上设置大小。 – 2010-05-20 11:36:28

+0

调整内部页面大小后,这不起作用 – VMAtm 2010-05-20 11:41:31