现在的位置: 首页 > 综合 > 正文

HOWTO: IE8下处理iframe自适应高度

2012年09月22日 ⁄ 综合 ⁄ 共 1010字 ⁄ 字号 评论关闭

老生常谈的问题, 网络上铺天盖地的处理方法, 还有抄来转去的"博文". 在此主要说明今日遇到的特定于IE8的一个特定问题.

function autoSetFrameHeight(name) {
    try {
        var iframe;
        if (!name) return;
        iframe = document.getElementById(name);
        if (iframe.contentDocument)
            $("#" + name).height(iframe.contentDocument.height + "px");
        else
            $("#" + name).height(document.frames[name].document.body.scrollHeight + "px");
    } catch (e) {
        // alert(e.message);
    }
}

今天有用户反应IE8下某个弹窗(iframe内嵌个小页面)显示不完全, 后经测试, iframe.contentDocument.heightIE8下无效, 在IE6-7, Chrome, Firefox3~4下

改为iframe.contentDocument.body.offsetHeight后, 在IE6-8, Chrome, Firefox3~4下测试通过.

   

本文的示例代码运行在真实项目中, 但由于iframe目标页面承载的内容较为简单, 因此并未测试iframe目标页面中包含绝对定位层展开/折叠, 以及包含float层的情况,

也未处理某些文章提及的"IE浏览器会有长高了缩不回去"的情形. 请读者注意.

   

參考資料: (請讀者自行驗證原文內容, 辯證接受)

  1. http://www.cnblogs.com/yuhe7919/archive/2009/11/04/iframe.html
  2. 此文中提及的代碼示例, 建議不要再採用了, 如果第一句取高度的代碼由於瀏覽器兼容性問題產生異常, 則此段代碼完全失效. 另外, 採用兩個高度比較的作法也沒有意義, 有些繞道並且繞遠了的感覺.

    try {

    var bHeight = iframe.contentWindow.document.body.scrollHeight;
    var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;

    } catch(ex) { }

抱歉!评论已关闭.