首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iframe 自適應高度只顯示一半的修復方案

     編輯:程式設計綜合問答

問題

iframe `onload` 獲取高度邏輯有誤,導致只顯示一半內容。

核心修正

function SetCwinHeight(obj, bl) {
    try {
        var doc = obj.contentDocument || obj.contentWindow.document;
        var scrollHeight = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight);
        var iht = parseInt(obj.getAttribute('iht')) || 490;
        
        if (scrollHeight > iht && bl === "true") {
            obj.style.height = (scrollHeight + 50) + 'px';
        } else {
            obj.style.height = iht + 'px';
        }
        // 寬度同理
    } catch (ex) { console.error(ex); }
}

關鍵點

  • 用 contentDocument 兼容 Firefox/Chrome,contentWindow.document 兼容 IE。
  • 取 Math.max(body.scrollHeight, documentElement.scrollHeight) 解決 XHTML DOCTYPE 導致 body.scrollHeight=0。
  • 屬性讀取用 getAttribute('iht'),代碼中 `ith`/`iht` 混用導致邏輯錯。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved