Implementação de altura automática para iframe com adaptação ao conteúdo interno

var browserVersion = navigator.userAgent.toUpperCase(); var isOpera = /OPERA/.test(browserVersion); var isFirefox = /FIREFOX/.test(browserVersion); var isChrome = /CHROME/.test(browserVersion); var isSafari = /SAFARI/.test(browserVersion); var isIE = !!(window.ActiveXObject || "ActiveXObject" in window); var isIE9Plus = !-[1,];

function adjustIframeHeight(iframeId, minHeight) { try { var iframe = document.getElementById(iframeId); var bodyHeight = 0; var docHeight = 0;

    if (!isChrome && !isSafari) {
        try {
            bodyHeight = iframe.contentWindow.document.body.scrollHeight;
        } catch (e) {}
    }

    if (isFirefox) {
        docHeight = iframe.contentWindow.document.documentElement.offsetHeight + 2;
    } else if (!isIE && !isOpera && iframe.contentWindow) {
        try {
            docHeight = iframe.contentWindow.document.documentElement.scrollHeight;
        } catch (e) {}
    } else if (isIE && isIE9Plus) {
        var deviation = bodyHeight - eval("window.IE9RealHeight" + iframeId);
        if (deviation === 0) {
            bodyHeight += 3;
        } else if (deviation !== 3) {
            eval("window.IE9RealHeight" + iframeId + " = " + bodyHeight);
            bodyHeight += 3;
        }
    } else {
        bodyHeight += 3;
    }

    var finalHeight = Math.max(bodyHeight, docHeight);
    if (finalHeight < minHeight) finalHeight = minHeight;
    iframe.style.height = finalHeight + "px";
} catch (e) {}

}

function startInit(iframeId, minHeight) { eval("window.IE9RealHeight" + iframeId + " = 0"); setInterval(function() { adjustIframeHeight(iframeId, minHeight); }, 100); }


</div><div>```

document.getElementById("mainFrame").style.height = "0px";
document.getElementById("mainFrame").src = url;

<body style="height:500px;">

Evite o uso de margin-bottom ou padding-bottom na última parte do conteúdo. Prefira o uso de <br/>.

Em ambientes locais, alguns navegadores podem bloquear o acesso a propriedades do iframe por motivos de segurança. Teste sempre em um servidor.

Compatibilidade

Testado e funcional em: IE6-11, Chrome, Firefox, Opera, Safari, Maxthon e 360 Browser.

Atulaizações

  • 2015-01-15 - Suporte adicionado para IE11
  • 2015-04-15 - Otimização do uso de setInterval para evitar múltiplas instâncias
  • 2016-03-30 - Correção para altura crescente em IE9+
  • 2016-05-24 - Ajuste para altura fatlando 3px em IE9+
  • 2018-04-14 - Correção para altura não reduzir em navegadores baseados no Chrome (ex: 360)

Alternativa com elemento específico

Para maior precisão, envolva o conteúdo do iframe com uma div com ID específico:


<body>
    <div class="content" id="main_content">
        ...
    </div>
</body>

E atualize o script principle:


var heightSetterTimer = null;

function adjustIframeHeight(iframeId, minHeight) {
    try {
        var iframe = document.getElementById(iframeId);
        var height = iframe.contentWindow.document.getElementById("main_content").offsetHeight;
        if (!height || height < minHeight) {
            height = minHeight;
        }
        iframe.style.height = height + "px";
    } catch (e) {
        iframe.style.height = minHeight + "px";
    }
}

function startHeightWatcher(iframeId, minHeight) {
    if (!heightSetterTimer) {
        eval("window.IE9RealHeight" + iframeId + " = 0");
        heightSetterTimer = setInterval(function() {
            adjustIframeHeight(iframeId, minHeight);
        }, 100);
    }
}

function navigateFrame(url) {
    if (heightSetterTimer) {
        clearInterval(heightSetterTimer);
        heightSetterTimer = null;
    }
    document.getElementById("mainFrame").style.height = "600px";
    document.getElementById("mainFrame").src = url;
    startHeightWatcher('mainFrame', 600);
}

Tags: iframe altura responsiva javascript compatibilidade navegadores DOM manipulation

Publicado em 9-24 08:32