jquery obtener la altura del contenido iframe cuando se carga


Tengo una página de Ayuda, ayuda.php que estoy cargando dentro de un iframe en main.php ¿Cómo puedo obtener la altura de esta página una vez que se ha cargado en el iframe?

Estoy preguntando esto porque no puedo estilizar la altura de to iframe al 100% o auto. Por eso creo que necesito usar javascript.. Estoy usando jQuery

CSS:

body {
    margin: 0;
    padding: 0;
}
.container {
    width: 900px;
    height: 100%;
    margin: 0 auto;
    background: silver;
}
.help-div {
    display: none;
    width: 850px;
    height: 100%;
    position: absolute;
    top: 100px;
    background: orange;
}
#help-frame {
    width: 100%;
    height: auto;
    margin:0;
    padding:0;
}

JS:

$(document).ready(function () {
    $("a.open-help").click(function () {
        $(".help-div").show();
        return false;
    })
})

HTML:

<div class='container'>
    <!-- -->
    <div class='help-div'>
        <p>This is a div with an iframe loading the help page</p>
        <iframe id="help-frame" src="../help.php" width="100%" height="100%" frameborder="1"></iframe>
    </div>  <a class="open-help" href="#">open Help in iFrame</a>

    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
</div>
Author: karthikr, 2010-10-02

7 answers

Ok Finalmente encontré una buena solución:

$('iframe').load(function() {
    this.style.height =
    this.contentWindow.document.body.offsetHeight + 'px';
});

Debido a que algunos navegadores (antiguos Safari y Opera) informan sobre la carga completada antes de que CSS se renderice, debe establecer un micro tiempo de espera y borrar y reasignar el src del iframe.

$('iframe').load(function() {
    setTimeout(iResize, 50);
    // Safari and Opera need a kick-start.
    var iSource = document.getElementById('your-iframe-id').src;
    document.getElementById('your-iframe-id').src = '';
    document.getElementById('your-iframe-id').src = iSource;
});
function iResize() {
    document.getElementById('your-iframe-id').style.height = 
    document.getElementById('your-iframe-id').contentWindow.document.body.offsetHeight + 'px';
}
 93
Author: FFish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-04 05:29:16

La respuesta menos complicada es usar .contents() para llegar al iframe. Curiosamente, sin embargo, devuelve un valor diferente de lo que obtengo usando el código en mi respuesta original, debido al relleno en el cuerpo, creo.

$('iframe').contents().height() + 'is the height'

Así es como lo he hecho para la comunicación entre dominios, así que me temo que es innecesariamente complicado. Primero, pondría jQuery dentro del documento del iFrame; esto consumirá más memoria, pero no debería aumentar el tiempo de carga ya que solo el script necesita ser cargado una vez.

Use el jQuery del iFrame para medir la altura del cuerpo del iframe lo antes posible (onDOMReady) y luego establezca el hash de URL a esa altura. Y en el documento padre, agregue un evento onload a la etiqueta iFrame que verá la ubicación del iframe y extraerá el valor que necesita. Debido a que onDOMReady siempre ocurrirá antes del evento de carga del documento, puede estar bastante seguro de que el valor se comunicará correctamente sin una condición de carrera complicando las cosas.

En otras palabras:

Help en ayuda.php:

var getDocumentHeight = function() {
    if (location.hash === '') { // EDIT: this should prevent the retriggering of onDOMReady
        location.hash = $('body').height(); 
        // at this point the document address will be something like help.php#1552
    }
};
$(getDocumentHeight);

...y en el documento padre:

var getIFrameHeight = function() {
    var iFrame = $('iframe')[0]; // this will return the DOM element
    var strHash = iFrame.contentDocument.location.hash;
    alert(strHash); // will return something like '#1552'
};
$('iframe').bind('load', getIFrameHeight );
 44
Author: Andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-03 01:44:36

Encontré lo siguiente para trabajar en Chrome, Firefox e IE11:

$('iframe').load(function () {
    $('iframe').height($('iframe').contents().height());
});

Cuando el contenido de Iframes termine de cargar, el evento se activará y establecerá la altura de IFrames a la de su contenido. Esto solo funcionará para las páginas dentro del mismo dominio que el del IFrame.

 16
Author: Jack Zach Tibbles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-11 06:09:12

No necesitas jquery dentro del iframe para hacer esto, pero lo uso porque el código es mucho más simple...

Ponga esto en el documento dentro de su iframe.

$(document).ready(function() {
  parent.set_size(this.body.offsetHeight + 5 + "px");  
});

Se agregaron cinco anteriores para eliminar la barra de desplazamiento en ventanas pequeñas, nunca es perfecto en tamaño.

Y esto dentro de su documento padre.

function set_size(ht)
{
$("#iframeId").css('height',ht);
}
 5
Author: RkaneKnight,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-26 18:44:38

El código para hacer esto sin jQuery es trivial hoy en día:

const frame = document.querySelector('iframe')
function syncHeight() {
  this.style.height = `${this.contentWindow.document.body.offsetHeight}px`
}
frame.addEventListener('load', syncHeight)

Para desenganchar el evento:

frame.removeEventListener('load', syncHeight)
 4
Author: cchamberlain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-02 14:51:00

Esta es la respuesta correcta que funcionó para mí

$(document).ready(function () {
        function resizeIframe() {
            if ($('iframe').contents().find('html').height() > 100) {
                $('iframe').height(($('iframe').contents().find('html').height()) + 'px')
            } else {
                setTimeout(function (e) {
                    resizeIframe();
                }, 50);
            }
        }
        resizeIframe();
    });
 0
Author: Javier Gordo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-15 20:23:05

Las respuestas aceptadas $('iframe').load ahora producirán a.indexOf is not a function error. Se puede actualizar a:

$('iframe').on('load', function() {
  // ...
});

Algunos otros similares a .load obsoletos desde jQuery 1.8: " Uncaught TypeError: a.indexOf is not a function " error al abrir un nuevo proyecto foundation

 0
Author: Ryan J. Stout,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-14 19:34:41